Child Processes
Choose between exec, execFile, spawn, and fork when work must run outside the main process.
Lesson content
🎯 Goal By the end of this lesson, you'll understand: What are Child Processes? Why do we use them? Types of Child Processes How they work Real-world examples Interview questions What are Child Processes? A Child Process is a separate process created by a Node.js application to execute another program or script. It allows Node.js to perform CPU-intensive tasks , run system commands , or execute other programs without blocking the Event Loop. Simple Definition: A Child Process is a new process created by Node.js to perform work independently. Why Do We Need Child Processes? JavaScript runs on a single thread . Heavy tasks like: Image Processing Video Encoding Running Python Scripts Executing Shell Commands Large File Compression can block the Event Loop. Child Processes solve this problem. Real-Life Example 👨💼 Imagine a manager in an office. Manager │ ▼ Assign Work │ ▼ Employee Works │ ▼ Manager Continues Other Work │ ▼ Employee Returns Result Manager → Parent Process Employee → Child Process Child Process Module Import the module: const { exec, spawn, fork, execFile } = require ( "child_process" ); Types of Child Processes Method Purpose exec() Execute a shell command and return complete output spawn() Start a process and stream data continuously fork() Create another Node.js process execFile() Execute a file directly without a shell 1. exec() Runs a shell command and returns the complete output. Example const { exec } = require ( "child_process" ); exec ( "node -v" , ( error , stdout , stderr ) => { console . log( stdout ); }); Output v22.x.x 2. spawn() Starts a process and returns output as a stream. Example const { spawn } = require ( "child_process" ); const child = spawn ( "node" , [ "--version" ]); child . stdout . on( "data" , ( data ) => { console . log( data . toString()); }); Output v22.x.x 3. fork() Creates a new Node.js process . parent.js const { fork } = require ( "child_process" ); const child = fork ( "child.js" ); child . send( "Hello Child" ); child.js process . on( "message" , ( msg ) => { console . log( msg ); }); Output Hello Child 4. execFile() Runs an executable file directly (without starting a shell). Example const { execFile } = require ( "child_process" ); execFile ( "node" , [ "--version" ], ( err , stdout ) => { console . log( stdout ); }); Output v22.x.x How Child Processes Work Node.js Application │ ▼ Create Child Process │ ▼ Child Executes Task │ ▼ Returns Result │ ▼ Parent Receives Output exec() vs spawn() Feature exec() spawn() Output Entire output at once Streamed output Memory Usage Higher Lower Best For Small output Large output Uses Shell ✅ Yes ❌ No (by default) spawn() vs fork() Feature spawn() fork() Run Any Program ✅ Yes ❌ No Run Node.js Script ✅ Yes ✅ Yes IPC (Message Passing) ❌ No ✅ Yes ( send() / message ) Best For External commands Node.js child processes Real-Life Example 📷 Photo Upload Upload Image │ ▼ Node.js Server │ ▼ Child Process (Image Resize) │ ▼ Return Resized Image The server remains responsive while the image is processed. Where Are Child Processes Used? ✅ Image Processing ✅ Video Encoding ✅ Running Python Scripts ✅ PDF Generation ✅ Shell Commands ✅ File Compression ✅ Backup Scripts Interview Question Which child process method is best for continuously reading large output? Answer: spawn() Because it streams data instead of buffering the entire output in memory. Best Practices ✅ Use spawn() for long-running processes or large output. ✅ Use exec() for short shell commands. ✅ Use fork() for Node.js-to-Node.js communication. ✅ Handle errors using the error event or callback. ❌ Avoid exec() with untrusted user input because shell command injection is a security risk. Key Points ✅ Child Processes run independently of the parent Node.js process. ✅ They prevent CPU-intensive work from blocking the Event Loop. ✅ exec() executes shell commands and buffers the output. ✅ spawn() streams output, making it suitable for large data. ✅ fork() creates a new Node.js process with built-in message passing. ✅ execFile() executes a file directly without using a shell. 🧠 Easy Formula Need Small Command? │ ▼ exec() Need Large Output? │ ▼ spawn() Need Another Node.js Process? │ ▼ fork() Need to Run an Executable File? │ ▼ execFile() exec() → Small Shell Command spawn() → Large Streaming Output fork() → Node.js Child Process execFile() → Execute File Directly Remember: 🚀 exec() = Small command, full output 🌊 spawn() = Large output, stream data 🔄 fork() = Create another Node.js process with IPC ⚙️ execFile() = Run an executable directly without a shell