Last active
December 5, 2022 18:38
-
-
Save ndelangen/3b2b981a4795e51ef4f8cf583764eb8a to your computer and use it in GitHub Desktop.
NodeJS child_process communication (IPC) example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (process.send) { | |
process.send("Hello"); | |
} | |
process.on('message', message => { | |
console.log('message from parent:', message); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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' }