node.js通过(派生的)child_process传递流

时间:2018-12-30 03:23:53

标签: node.js child-process

我正在尝试与node.js中的(分支)子进程进行通信。

背景是我想在另一个线程中运行流。

我有一个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)
...

1 个答案:

答案 0 :(得分:0)

我的直觉是,您不能仅在另一个线程中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