我有一个 test1.ts 文件,我试图将一些 CPU 密集型图像处理工作卸载到工作线程。下面是文件 test1.ts 的代码及其在另一个文件中的调用。该项目是一个 NodeJS ExpressJS Web 服务器。
test1.ts 文件
const { Worker, workerData,isMainThread, parentPort } = require("worker_threads");
const { generateUrls } = require("./util");
const Jimp = require("jimp");
const { uploadImage } = require("../imageStorage");
if (!isMainThread){
mainWork()
.finally(() => {
parentPort?.postMessage({});
})
}
async function mainWork() {
const { accountId, imageBuffer, imageNames, docUrls, meta } = workerData;
try {
const { imageIndex, imageType } = meta;
const imageName = imageNames.imageName + `_${imageType}_` + `${imageIndex || ""}` + ".png";
docUrls[imageType === "heatmap" ? "heatmapUrls" : "normalUrls"][imageIndex] = generateUrls(
accountId,
imageName
);
const maxWidth = 764;
const maxHeight = 2000;
const image = await Jimp.read(imageBuffer);
const originalWidth = image.bitmap.width;
const originalHeight = image.bitmap.height;
// Calculate the aspect ratio
const aspectRatio = originalWidth / originalHeight;
// Determine the new dimensions based on the desired maximum width and height
let newWidth = originalWidth;
let newHeight = originalHeight;
if (originalWidth > maxWidth) {
newWidth = maxWidth;
newHeight = maxWidth / aspectRatio;
}
if (newHeight > maxHeight) {
newHeight = maxHeight;
newWidth = maxHeight * aspectRatio;
}
image.resize(newWidth, newHeight);
image.quality(100);
const newBuffer = await image.getBufferAsync(Jimp.MIME_PNG);
await uploadImage(newBuffer, accountId, imageName);
return { imageName, docUrls }; // Return the result
} catch (error) {
console.error("Error resizing and converting image:", error);
return Promise.reject(error); // Reject the Promise with the error
}
}
function imageResizeCropUpload(
accountId: any,
imageBuffer: any,
imageNames: any,
docUrls: any,
meta: any
): Promise<void> {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
workerData: {
accountId,
imageBuffer,
imageNames,
docUrls,
meta
}
});
worker.on("message", (result:any) => {
resolve(result); // Resolve the Promise with the result
});
worker.on("error", (e:any) => {
reject(e);
});
worker.on("exit", (code:any) => {
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}
export default imageResizeCropUpload
一些其他文件.ts
import imageResizeCropUpload from './test1'
uploadPromises.push(
imageResizeCropUpload(accountId, buffers[0], imageNames, docUrls, {
imageIndex: 0,
imageType: "heatmap"
})
);
现在发生了什么,我不知道,但我得到的只是“Worker stop with exit code 1”,并出现错误,因为 process.send() 不是函数。我在网上查看但找不到任何东西。请帮助我,我是第一次使用工作线程。
process.send()
是在使用 child_process.fork()
创建的 Node.js 进程中使用的函数。该函数允许子进程与其父进程进行通信。在您的场景中,您遇到错误是因为您使用的是worker_threads,而不是child_process。工作线程模块没有 process.send()
函数,因为工作线程通过不同的机制与其主线程通信,特别是使用parentPort.PostMessage()
https://nodejs.org/api/worker_threads.html
https://nodejs.org/api/child_process.html
对
process.send()
的调用可能在Jimp或imageStorage中,如果是这种情况,您可能需要更改为使用子进程。