node.js 通过管道从( fork 的)child_process 中输出流

标签 node.js child-process

我正在尝试与 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/

相关文章:

PHP 环境变量转移到子进程中

perl - Perl中子进程从父进程继承的模块

arrays - .splice(x,1) 不起作用

javascript - 如何运行/执行部署在heroku上的应用程序

javascript - hapi.js Cors 飞行前不返回 Access-Control-Allow-Origin header

python - 在 gulp 中运行带参数的命令

linux - "Failed to execute child process (no such file or directory)"

javascript - 合并两个相似的 JSON 对象,但一个在 NodeJS 中具有更多键

node.js - 最佳实践 : Angular SSR Partial Pre-rendering with dynamic fallback

javascript - 您能否生成一个用与 Python 或 PHP 服务器不同的语言编写的子进程,就像使用 Node.js 一样?