0
0
Node.jsframework~5 mins

fork for Node.js child processes in Node.js

Choose your learning style9 modes available
Introduction

Fork lets you run another Node.js script as a separate process. This helps your app do many things at once without slowing down.

You want to run a heavy task without freezing your main app.
You need to run multiple scripts at the same time.
You want to keep your app responsive while doing background work.
You want to communicate between processes easily.
You want to separate parts of your app for better organization.
Syntax
Node.js
import { fork } from 'child_process';

const child = fork('script.js', ['arg1', 'arg2'], {
  cwd: '/path/to/dir',
  env: { ...process.env, CUSTOM_VAR: 'value' },
  silent: false
});

The first argument is the path to the script you want to run.

You can pass arguments as an array to the child script.

Examples
Runs worker.js as a child process with no extra arguments.
Node.js
import { fork } from 'child_process';

const child = fork('worker.js');
Passes two arguments to worker.js which it can access via process.argv.
Node.js
import { fork } from 'child_process';

const child = fork('worker.js', ['task1', 'task2']);
Runs the child process silently, so its output won't show in the parent console.
Node.js
import { fork } from 'child_process';

const child = fork('worker.js', [], { silent: true });
Sample Program

This example shows how to fork a child process running worker.js. The parent sends a message to start a task. The child listens for this message and replies back. This way, both processes talk to each other without blocking.

Node.js
import { fork } from 'child_process';

// Fork a child process to run worker.js
const child = fork('./worker.js');

// Listen for messages from the child
child.on('message', (msg) => {
  console.log('Message from child:', msg);
});

// Send a message to the child
child.send({ task: 'start' });

// worker.js content:
// process.on('message', (msg) => {
//   if (msg.task === 'start') {
//     process.send('Task started');
//   }
// });
OutputSuccess
Important Notes

Child processes run independently but can communicate using messages.

Use child.send() and process.on('message') to talk between parent and child.

Remember to handle errors and exit events to avoid zombie processes.

Summary

fork runs another Node.js script as a separate process.

It helps keep your app fast by doing work in parallel.

You can send messages back and forth between parent and child.