Child Processes

Back

Loading concept...

๐Ÿญ Node.js Child Processes: Your Factory of Little Helpers

The Big Idea in 30 Seconds

Imagine youโ€™re a chef running a busy restaurant kitchen. Youโ€™re amazing, but you can only cook one dish at a time. What if you could hire helper chefs to work alongside you? Each helper can cook a different dish at the same time!

Thatโ€™s exactly what child processes do in Node.js. Your main program (the parent) can create little helper programs (the children) to do work simultaneously.

๐ŸŽฏ One sentence: Child processes let your Node.js app do many things at once by creating separate mini-programs.


๐ŸŒŸ What is child_process?

Think of child_process as your hiring agency. Itโ€™s a built-in Node.js module that helps you create and manage helper workers.

// Importing the hiring agency
const { spawn, exec, fork }
  = require('child_process');

What Can These Helpers Do?

Helper Task Real Example
Run system commands List files, create folders
Execute other programs Run Python scripts
Process heavy calculations Image processing
Run other Node.js files Parallel data processing

๐Ÿ”จ Creating Child Processes

You have three main ways to hire helpers. Think of them like different types of workers:

1. spawn() โ€“ The Steady Worker ๐Ÿƒ

Best for: Long-running tasks with streaming output.

Imagine a worker who talks to you constantly while working. Every time they find something, they tell you immediately.

const { spawn } = require('child_process');

// Ask helper to list files
const helper = spawn('ls', ['-la']);

// Helper streams results back
helper.stdout.on('data', (data) => {
  console.log(`Found: ${data}`);
});

2. exec() โ€“ The Report Writer ๐Ÿ“

Best for: Quick tasks where you want all results at once.

Like a helper who goes away, does the work, and comes back with a complete report.

const { exec } = require('child_process');

// Helper works and returns everything
exec('ls -la', (error, stdout, stderr) => {
  console.log('Complete report:', stdout);
});

3. fork() โ€“ The Special Assistant ๐Ÿค

Best for: Running other Node.js files with easy communication.

Like hiring another chef who speaks your language perfectly. You can send messages back and forth easily!

const { fork } = require('child_process');

// Hire another Node.js chef
const assistant = fork('helper.js');

// Send them a message
assistant.send({ task: 'make pizza' });

๐Ÿ“ก Child Process Events

When you hire a helper, you need to know whatโ€™s happening! Child processes send you signals (events) about their work.

graph TD A["Child Process"] --> B["๐ŸŽ‰ spawn: I'm born!] A --> C[๐Ÿ“ค data: Here's output!"] A --> D["โš ๏ธ error: Something broke!"] A --> E[๐Ÿšช close: I'm done!] A --> F["๐Ÿ’€ exit: Goodbye!"]

The Key Events Explained

Event When It Fires What It Means
spawn Process starts โ€œIโ€™m alive!โ€
data Output arrives โ€œHereโ€™s some info!โ€
error Something fails โ€œHelp, Iโ€™m stuck!โ€
close Streams shut โ€œPacking up nowโ€
exit Process ends โ€œMy work is doneโ€

Listening to Events

const { spawn } = require('child_process');
const child = spawn('node', ['worker.js']);

// When child starts
child.on('spawn', () => {
  console.log('Helper started! ๐ŸŽ‰');
});

// When child sends output
child.stdout.on('data', (data) => {
  console.log('Helper says:', data);
});

// When child finishes
child.on('exit', (code) => {
  console.log(`Helper done! Exit: ${code}`);
});

๐Ÿ’ฌ IPC: Talking to Your Children

IPC stands for Inter-Process Communication. Itโ€™s how parent and child talk to each other.

Think of it like walkie-talkies between you and your helper! ๐Ÿ“ป

The Magic of fork() and IPC

When you use fork(), you get a built-in chat channel:

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

// Send message to child
child.send({ job: 'calculate', num: 42 });

// Listen for child's reply
child.on('message', (msg) => {
  console.log('Child replied:', msg);
});
// === child.js ===
// Listen for parent's message
process.on('message', (msg) => {
  console.log('Got job:', msg);

  // Do the work
  const result = msg.num * 2;

  // Reply to parent
  process.send({ result: result });
});

How IPC Works

graph LR P["๐Ÿ‘จ Parent"] -->|send| C["๐Ÿ‘ถ Child"] C -->|send| P style P fill:#4ECDC4 style C fill:#FF6B6B

Important: IPC only works with fork(), not spawn() or exec()!


โš”๏ธ exec vs spawn vs fork: The Showdown

Hereโ€™s the ultimate comparison to know which one to use:

Quick Decision Chart

graph TD Q["What do you need?"] --> A{Running Node.js?} A -->|Yes| F["Use fork ๐Ÿค"] A -->|No| B{Need streaming?} B -->|Yes| S["Use spawn ๐Ÿƒ"] B -->|No| E["Use exec ๐Ÿ“"]

Side-by-Side Comparison

Feature exec spawn fork
Output All at once Stream Stream
Buffer Limited (~1MB) Unlimited Unlimited
Shell Yes (auto) No (manual) No
IPC โŒ No โŒ No โœ… Yes!
Best for Quick commands Long tasks Node.js files

When to Use Each

Use exec() when:

  • Running simple shell commands
  • Output is small (under 1MB)
  • You want the result as a string
exec('whoami', (err, stdout) => {
  console.log('User:', stdout.trim());
});

Use spawn() when:

  • Processing large amounts of data
  • You need real-time output
  • Running long-running processes
const video = spawn('ffmpeg', ['-i', 'input.mp4']);
video.stdout.pipe(process.stdout);

Use fork() when:

  • Running another Node.js script
  • You need two-way communication
  • Building a worker pool
const worker = fork('heavy-math.js');
worker.send({ calculate: 'fibonacci' });

๐ŸŽฎ Real-World Example: A Mini Task System

Letโ€™s build something practical! A parent that delegates math to a child:

// === boss.js (Parent) ===
const { fork } = require('child_process');

const worker = fork('math-worker.js');

// Give the worker a task
worker.send({
  task: 'add',
  numbers: [1, 2, 3, 4, 5]
});

// Get the answer back
worker.on('message', (result) => {
  console.log('Sum is:', result.answer);
  worker.kill(); // Thank you, worker!
});
// === math-worker.js (Child) ===
process.on('message', (msg) => {
  if (msg.task === 'add') {
    const sum = msg.numbers
      .reduce((a, b) => a + b, 0);

    process.send({ answer: sum });
  }
});

๐Ÿง  Key Takeaways

  1. child_process = Your toolbox for creating helper programs
  2. spawn = For streaming data, long tasks
  3. exec = For quick commands, small output
  4. fork = For Node.js files with IPC chat
  5. Events = How you know whatโ€™s happening
  6. IPC = The walkie-talkie between parent and child

๐Ÿš€ Youโ€™ve Got This!

Think of yourself as the head chef now. You know how to:

  • Hire helpers (spawn, exec, fork)
  • Listen to their updates (events)
  • Talk back and forth (IPC)
  • Choose the right helper for each job

Go forth and build amazing, concurrent Node.js applications! ๐ŸŽ‰

โ€œOne process is powerful. Many processes are unstoppable.โ€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.