Child Process
suggest changeChild processes are the way to run work in a separate operating-system process, with its own initialization. child_process.fork() starts another Node.js process and gives it an IPC channel. It is not a thread (worker_threads is the thread API). Cluster workers are themselves forked child processes, and they can message their parent the same way.
The communication goes both ways, so parent and child can listen for messages and send messages.
Parent (../parent.js)
var child_process = require('child_process');
console.log('[Parent]', 'initialize');
var child1 = child_process.fork(__dirname + '/child');
child1.on('message', function(msg) {
console.log('[Parent]', 'Answer from child: ', msg);
});
// one can send as many messages as one wants
child1.send('Hello'); // Hello to you too :)
child1.send('Hello'); // Hello to you too :)
// one can also have multiple children
var child2 = child_process.fork(__dirname + '/child');
Child (../child.js)
// here would one initialize this child
// this will be executed only once
console.log('[Child]', 'initialize');
// here one listens for new tasks from the parent
process.on('message', function(messageFromParent) {
//do some intense work here
console.log('[Child]', 'Child doing some intense work');
if(messageFromParent == 'Hello') process.send('Hello to you too :)');
else process.send('what?');
})
Besides message, the child can emit many events, such as error, connected, and disconnect.
Starting a child process has a certain cost associated with it. One would want to spawn as few of them as possible.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents