我正在尝试与 Node.js 中的( fork 的)子进程进行通信。
背景是我想在另一个线程中运行一个流。
我有一个nodejs父进程,它启动另一个nodejs子进程。子进程执行一些逻辑,然后将输出返回给父进程。
父文件代码:
const stream = require('stream');
const Writable = stream.Writable;
const fork = require("child_process").fork;
class Logger extends Writable {
constructor() {
super({ objectMode: true });
}
_write(chunk, encoding, callBack) {
console.log(`${Date.now()} - (payload:${chunk})`);
callBack(null);
}
}
const writeStream = new Logger();
const computedStream = fork('child.js', [], { silent: true });
computedStream.stdout
.pipe(writeStream);
子文件代码:
const stream = require('stream');
const Readable = stream.Readable;
class RandomNumberGenerator extends Readable {
constructor() {
super({ objectMode: true });
this._count = 10;
this._counter = 0;
}
_read() {
if (this._counter === this._count) {
return this.push(null);
}
const random = Math.random();
this.push(random)
this._counter++;
}
}
const readStream = new RandomNumberGenerator();
readStream.pipe(process.stdout);
上面的代码什么也没打印出来,我正在等待。像这样
1546139560637 - (payload:0.05907150771370184)
1546139560642 - (payload:0.395942443503438)
1546139560642 - (payload:0.7873116185362699)
...
最佳答案
我的预感是,您不能只是在另一个线程中使用 console.log
并期望它在主线程上输出。您需要将信息发回,然后在主线程上 console.log 。
鉴于结果正确地位于 process.stdout
Child.js
// After all processing has finished on the child thread
process.send({ info: process.stdout });
父文件代码
const computedStream = fork('child.js', [], { silent: true });
computedStream.on('message', (message) => {
console.log(`stdout of child processes is: ${message.info}`);
});
更多信息可以在这里找到 - https://itnext.io/multi-threading-and-multi-process-in-node-js-ffa5bb5cde98
关于node.js 通过管道从( fork 的)child_process 中输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975046/