0
0
Node.jsframework~5 mins

IPC communication between processes in Node.js

Choose your learning style9 modes available
Introduction

IPC lets different programs or parts of a program talk to each other. It helps them share data or commands easily.

When you want a main program to control smaller helper programs.
When you need to split a big task into smaller parts running at the same time.
When different programs need to share information quickly.
When you want to keep your app responsive by running heavy work in another process.
When you want to safely separate parts of your app for security or stability.
Syntax
Node.js
const { fork } = require('child_process');

const child = fork('child.js');

child.on('message', (msg) => {
  console.log('Message from child:', msg);
});

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

fork() creates a new Node.js process that can talk with the parent.

Use send() to send messages and on('message') to receive them.

Examples
Send a simple string message to the child process.
Node.js
const { fork } = require('child_process');
const child = fork('child.js');
child.send('start');
Listen for messages from the child process and print them.
Node.js
child.on('message', (msg) => {
  console.log('Got:', msg);
});
Send an object with task details to the child process.
Node.js
child.send({ task: 'compute', data: 42 });
Sample Program

This example shows a parent process creating a child process. The parent sends a greeting object. The child receives it, prints it, and replies back. The parent then prints the reply.

Node.js
// parent.js
const { fork } = require('child_process');

const child = fork('./child.js');

child.on('message', (msg) => {
  console.log('Parent got:', msg);
});

child.send({ greeting: 'Hello Child' });

// child.js
process.on('message', (msg) => {
  console.log('Child got:', msg);
  process.send({ reply: 'Hello Parent' });
});
OutputSuccess
Important Notes

Messages sent between processes must be serializable (like objects or strings).

IPC is asynchronous, so messages may arrive in any order.

Use IPC to keep your app fast by offloading work to child processes.

Summary

IPC lets Node.js processes talk by sending messages.

Use fork() to create child processes that communicate with the parent.

Send and receive messages with send() and on('message').