有问题的示例项目:https ://github.com/Suvtruf/bcrypt-child-process-crash-proof
const {Worker, isMainThread} = require('worker_threads');
if(isMainThread)
console.log("I'm ok, because I'm alpha main");
else
console.log("I'm sad, because I can't load bcrypt");
const bcrypt = require('bcrypt');
function runTestWorker(workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker('./index.js', workerData);
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
})
})
}
async function run() {
const result = await runTestWorker('I will crash your app (。•́︿•̀。)');
console.log(result);
}
if(isMainThread)
run().catch(err => console.error(err));
如果你试图在工作线程中加载 bcrypt,你会得到错误:
Error: Module did not self-register.
at Object.Module._extensions..node (internal/modules/cjs/loader.js:779:18)
at Module.load (internal/modules/cjs/loader.js:630:32)
at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
at Function.Module._load (internal/modules/cjs/loader.js:562:3)
at Module.require (internal/modules/cjs/loader.js:667:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (O:\Texts\Sources\my\bcrypt-child-process-crash-proof\node_modules\bcrypt\bcrypt.js:6:16)
at Module._compile (internal/modules/cjs/loader.js:738:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
at Module.load (internal/modules/cjs/loader.js:630:32)
信息:
- 节点 v11.10.0
- bcrypt v3.0.4
我该如何解决?