Child processes let Node.js run multiple tasks at the same time. This helps when one task takes a long time and you don't want to stop everything else.
Why child processes are needed in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const { fork } = require('child_process');
const child = fork('script.js');
child.on('message', (msg) => {
console.log('Message from child:', msg);
});
child.send('Hello child');fork() creates a new Node.js process to run a separate script.
You can send messages back and forth between the main and child processes.
Examples
exec to run a shell command and get its output.Node.js
const { exec } = require('child_process');
exec('ls -l', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
console.log(`Output:\n${stdout}`);
});spawn runs a command and streams its output live.Node.js
const { spawn } = require('child_process');
const child = spawn('node', ['script.js']);
child.stdout.on('data', (data) => {
console.log(`Child output: ${data}`);
});fork creates a child Node.js process that can communicate with the parent.Node.js
const { fork } = require('child_process');
const child = fork('worker.js');
child.send({ task: 'start' });
child.on('message', (msg) => {
console.log('Received from child:', msg);
});Sample Program
This program creates a child process that runs worker.js. It sends a message to start work and listens for replies. This keeps the main app free to do other things.
Node.js
const { fork } = require('child_process');
// Fork a child process to run worker.js
const child = fork('./worker.js');
// Send a message to the child
child.send('Start work');
// Listen for messages from the child
child.on('message', (msg) => {
console.log('Message from child:', msg);
});Important Notes
Child processes run independently, so if one crashes, it won't crash the main app.
Use child processes to improve app speed and responsiveness.
Summary
Child processes let Node.js do many things at once.
They keep your app from freezing during heavy tasks.
You can send messages between main and child processes easily.
Practice
1. Why do Node.js applications use child processes?
easy
Solution
Step 1: Understand Node.js single-threaded nature
Node.js runs JavaScript in a single thread, so heavy tasks can block the app.Step 2: Role of child processes
Child processes run tasks separately, so the main app stays responsive.Final Answer:
To run heavy tasks without freezing the main app -> Option CQuick Check:
Child processes prevent freezing = B [OK]
Hint: Child processes keep main app responsive during heavy work [OK]
Common Mistakes:
- Thinking child processes speed up internet loading
- Confusing file size with process management
- Believing child processes update Node.js automatically
2. Which of the following is the correct way to create a child process in Node.js?
easy
Solution
Step 1: Recall Node.js child process methods
The 'child_process' module has methods like fork(), spawn(), exec(), but not start() or run().Step 2: Identify correct method for creating a child process running a script
fork() is used to create a new Node.js process running a script file.Final Answer:
const child = require('child_process').fork('script.js'); -> Option AQuick Check:
fork() creates child process = A [OK]
Hint: Use fork() to create child Node.js processes [OK]
Common Mistakes:
- Using non-existent methods like start() or run()
- Confusing exec() with fork() for script processes
- Forgetting to require 'child_process' module
3. What will be the output of this Node.js code snippet?
Assuming
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Message from child:', msg);
});
child.send('Hello');Assuming
child.js sends back the message { reply: 'Hi' } when it receives a message.medium
Solution
Step 1: Understand message passing between parent and child
The parent sends 'Hello' to child.js, which replies with { reply: 'Hi' }.Step 2: Check event listener for 'message'
The parent listens for messages from child and logs them with prefix 'Message from child:'.Final Answer:
Message from child: { reply: 'Hi' } -> Option DQuick Check:
Child replies logged correctly = D [OK]
Hint: Child sends message, parent logs with 'Message from child:' prefix [OK]
Common Mistakes:
- Confusing sent and received messages
- Expecting error from child.send() which is valid
- Assuming child.js does not run without error
4. Identify the error in this Node.js code using child processes:
const { fork } = require('child_process');
const child = fork('worker.js');
child.send('start');
child.on('message', (msg) => {
console.log(msg);
});
child.on('error', (err) => {
console.error('Child error:', err);
});medium
Solution
Step 1: Check order of send() and event listeners
It's valid to call send() before setting up 'message' listener; messages will queue.Step 2: Verify required event handlers and module import
Module is required correctly; 'error' event is handled; 'exit' event is optional.Final Answer:
No error; code is correct -> Option BQuick Check:
Code follows child process patterns = C [OK]
Hint: send() can be called anytime; event listeners catch messages/errors [OK]
Common Mistakes:
- Thinking send() must come after 'message' listener
- Expecting mandatory 'exit' event handling
- Missing module import (not in this code)
5. You want to perform a CPU-heavy task in Node.js without blocking the main event loop. Which approach best uses child processes to achieve this?
hard
Solution
Step 1: Identify how to avoid blocking main event loop
Heavy CPU tasks block the single-threaded main loop, causing freezes.Step 2: Use child processes to run heavy tasks separately
fork() creates a separate Node.js process to run the task without blocking.Step 3: Communicate results safely
Use message passing between main and child process to get results asynchronously.Final Answer:
Use fork() to run the heavy task in a separate process and communicate results via messages -> Option AQuick Check:
fork() isolates heavy tasks = A [OK]
Hint: fork() runs heavy tasks separately, keeping main loop free [OK]
Common Mistakes:
- Using setTimeout to delay heavy tasks (does not prevent blocking)
- Using exec() which can block main thread
- Loading heavy tasks synchronously with require()
