Search code examples
node.jschild-process

NodeJS subprocess.send() fails silently


I'm using child_process.fork() to spawn a child process, but calls from the parent to child via subprocess.send() fail silently (despite happening inside subprocess.on('spawn') callback); specifically, the child's process.on('message') does not trigger. Strangely, calls from the child to parent via process.send() work just fine. The call to subprocess.send returns true, which, according to the docs means it was successful; and no error is triggered from the child.

Parent.js:

const subprocess = fork(…);
subprocess.on('error', console.error);
subprocess.on('message', console.log);
// subprocess.on(eventName, console.log) for all other events
subprocess.on('spawn', () => {
  subprocess.send({ hello: 'child' }); // return's boolean `true`
});

Sub.js:

process.on('message', console.log); // nothin'
process.send({ hello: 'parent' }); // ← parent's on message triggered

Both subprocess.connected and the child's process.connected are true


Solution

  • This is a bug and has existed since the spawn event was added in v15.1: nodejs/node#37782

    It occurs only with ESM (import) and not commonjs (require).