我正在研究nodejs worker_threads。我想在服务器启动时撤消一个工作程序:
#!/usr/bin/env node
const bole = require('bole');
const { Worker } = require('worker_threads');
const path = require('path');
const config = require('./config');
// Use whichever logging system you prefer.
// Doesn't have to be bole, I just wanted something more or less realistic
const app = require('./app');
bole.output({ level: 'debug', stream: process.stdout });
const log = bole('server');
log.info('server process starting');
// Note that there's not much logic in this file.
// The server should be mostly "glue" code to set things up and
// then start listening
app.listen(config.express.port, config.express.ip, function(error) {
if (error) {
log.error('Unable to listen for connections', error);
process.exit(10);
}
log.info(`express is listening on http://${config.express.ip}:${config.express.port}`);
const worker = new Worker('./worker.js');
worker.on('message', msg => {
console.log(msg);
});
});
这是我的工作文件:
// eslint-disable-next-line import/no-unresolved
import { parentPort } from 'worker_threads';
parentPort.on('message', data => {
});
parentPort.postMessage('Hello world!');
但是它不起作用。我在Internet上尝试了其他示例,它们运行良好,但是未能将其实现到我的服务器上。我正在运行节点v12.0.0。
答案 0 :(得分:0)
首先,不太确定您如何提供工作文件的路径。 您已经导入了“路径”模块,但从未使用过。 所以也许研究一下。
第二个也是更重要的一点是,工作程序会返回一个Promise,因此将您的代码绑定到一个Promise中,当mainThread从worker接收到该Promise时,该Promise就将得到解决。