Reputation: 1964
I have a NodeJS child process listening for messages with process.on('message', callback)
however the process is exiting immediately. From my reading this is not supposed to happen since I have a callback waiting on the event loop so why is NodeJS exiting?
The example code below should be able to run as a standalone NodeJS process and not exit, correct?
Node Version: 7.3.0
example code:
function handle(msg) {
//do work here
}
process.on('message', (msg) => {
handle(msg);
}
Upvotes: 2
Views: 1246
Reputation: 3645
Here's a sample program that emulates your problem.
master.js
const cp = require('child_process');
const child = cp.spawn('node', ['./child.js'], {stdio: ['ipc']})
child.stdout.on('data', data => console.log(data.toString()))
child.send('immediate execute MESSAGE 1')
setTimeout(() => {
child.send('late execute MESSAGE 2 after 4 seconds')
}, 4000)
child.js
function handle(msg) {
console.log('Handling message -> ', msg);
}
process.on('message', (msg) => {
handle(msg);
});
process.on('exit', () => {
process.disconnect();
});
The key things to note here are -
child_process.spawn
- spawn returns a Buffer, and you can start listening to the stdout stream as soon as the child process starts.{stdio: ['ipc']}
- this option lets you open an IPC channel with the spawned child process. When you want to disconnect the child, simply use child.disconnect()
. Upvotes: 1