A fundamental part of Node's design is to create or fork processes when parallelizing execution or scaling a system, as opposed to creating a thread pool, for instance.
To create a child process, require Node's child_process module, and call the fork method. Pass the name of the program file the new process should execute:
// parent process
let cp = require('child_process');
let child = cp.fork(__dirname + '/child-process.js');
child.on('message', (m) => {
console.log('child said: ', m); //Parent got a message up from our child
});
child.send('I love you') // Send a message down to our child
// child process
process.on('message', (m) => {
console.log('parent said: ', m);
process.send('I love you too');
});
ps -A | grep node
The following program will start a network server, fork a child process, and pass the server reference from the parent down to the child:
// net-parent.js
const path = require('path');
let child = require("child_process").fork(path.join(__dirname, "net-child.js"));
let server = require("net").createServer();
server.on("connection", (socket) => {
socket.end("Parent handled connection");
});
server.listen(8080, () => {
child.send("Parent passing down server", server);
});
// net-child.js
process.on("message", function(message, server) {
console.log('net-child side: ', message);
server.on("connection", function(socket) {
socket.end("Child handled connection");
});
});
// another client.js
let net = require("net");
let sock = net.connect(8088);
process.stdin.pipe(sock);
sock.pipe(process.stdout);