Blog>
Snippets

Integrating Child Process for CPU-bound Tasks

Use the child_process module to offload a CPU-intensive task and maintain a non-blocking event loop.
const { fork } = require('child_process');

// Function that will perform the CPU-bound task
function performComputation() {
  // Computational heavy task (e.g., find a large fibonacci number)
  let result = 0;
  for (let i = 0; i < 1e9; i++) {
    result += i;
  }
  return result;
}
This is the computational heavy function that is supposed to run in a child process to avoid blocking the main event loop.
const child = fork('compute.js'); // Assuming 'compute.js' is where performComputation function resides

// Handle messages from the child process
child.on('message', (result) => {
  console.log(`Received result from child process: ${result}`);
});

// Send a message to the child process to start the computation
child.send({ command: 'start' });
This sets up the main process to fork a new child process that runs the 'compute.js' script and establishes message handlers to receive results from the child process.
// In compute.js
const { parentPort } = require('worker_threads');

parentPort.on('message', (message) => {
  if (message.command === 'start') {
    const result = performComputation();
    parentPort.postMessage(result);
  }
});
This is the code that would be inside 'compute.js', which is executed by the child process. It handles the message from the parent process, performs the computation, and sends the result back.