2024

Multi-Process Life

Today, I learnt how I could have multiple scripts messaging eachother in a Node.js environment. It's very similar in principle to recent modern additions to the web standard such as web workers.

// File: parent.js

import { fork } from 'child_process';

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

child
  .on('message', function (message) {
    console.log('Message from child:', message);
  })
  .on('exit', function (code, signal) {
    console.log(`Child process exited with code ${code} and signal ${signal}`);
  })
  .on('error', function (error) {
    console.log(error);
  });

child.send('Message from parent');
// File: child.js

process.on('message', function (message) {
  process.send('Message from parent:', message);
});