I am trying to communicate with a (forked) child-process from in node.js.
The background is that I want to run a stream in another thread.
I have a nodejs parent process that starts up another nodejs child process. The child process executes some logic and then returns output to the parent.
Parent File Code:
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); Child file code:
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); The above code prints out nothing and i am waiting for sth. like this
1546139560637 - (payload:0.05907150771370184) 1546139560642 - (payload:0.395942443503438) 1546139560642 - (payload:0.7873116185362699) ...