Skip to content

Instantly share code, notes, and snippets.

@ndelangen
Last active December 5, 2022 18:38
Show Gist options
  • Save ndelangen/3b2b981a4795e51ef4f8cf583764eb8a to your computer and use it in GitHub Desktop.
Save ndelangen/3b2b981a4795e51ef4f8cf583764eb8a to your computer and use it in GitHub Desktop.
NodeJS child_process communication (IPC) example
if (process.send) {
process.send("Hello");
}
process.on('message', message => {
console.log('message from parent:', message);
});
const fork = require('child_process').fork;
const program = path.resolve('child.js');
const parameters = [];
const options = {
stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ]
};
const child = fork(program, parameters, options);
child.on('message', message => {
console.log('message from child:', message);
child.send('Hi');
});
@ndelangen
Copy link
Author

Each child has 1 parent, they can communicate with, A parent can spawn and communicate with any amount of children.

@saeedjhn
Copy link

saeedjhn commented Jan 2, 2022

app.js
`const { fork } = require('child_process');
const process = require('process');

console.log('proccessID in parent:', process.pid);

const child = fork('child.js', [], {});

child.on('message', (msg) => {
console.log('The message between IPC channel, in app.js\n', msg);
});

child.send({ helloWorld: 'hello world' });

child.js
`const process = require('process');
const { fork } = require('child_process');

const child2 = fork('child2.js', [], {});

console.log('processID in child', process.pid);

process.on('message', (msg) => child2.send(msg));

child2.on('message', (msg) => process.send(msg));`

child2.js
`const process = require('process');

console.log('processID in child2 ', process.pid);

process.on('message', (msg) => {
console.log('The message between IPC channel, in child2.js:\n', msg);
});

process.send({ feedback: 'hello world' });`

result:
proccessID in parent: 61141
processID in child 61152
processID in child2 61159
The message between IPC channel, in app.js
{ feedback: 'hello world' }
The message between IPC channel, in child2.js:
{ helloWorld: 'hello world' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment