Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js process.kill() Method
Next article icon

Node Child Process

Last Updated : 27 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

NodeJS is designed to be single-threaded, but it provides a child_process module to create and manage child processes. This allows you to run system commands, execute other scripts, and perform computationally expensive tasks in parallel. The child process module is essential for tasks like running shell commands, spawning worker processes, and integrating with other programs.

What is a Child Process?

A child process is a separate process that is created and managed by the parent process (your NodeJS application). This allows you to run system commands (like listing files or checking memory usage)

  • Execute scripts (like Python, Bash, or another NodeJS script)
  • Perform CPU-intensive operations without blocking the main event loop
  • Create multiple processes that run in parallel (multi-threading in NodeJS)

The child_process module in NodeJS provides four methods to create child processes:

  1. spawn: Launches a new process with a given command. It streams data between the parent and child processes.
  2. exec: Runs a command in a shell and buffers the output. It’s useful for short-running commands.
  3. execFile: Similar to exec, but it runs a specific executable file directly without a shell.
  4. fork: A special case of spawn used to create NodeJS child processes. It enables communication between parent and child processes using send and on(‘message’).

Methods to Create Child Processes

1. spawn() method

The spawn() method launches a new process with a specified command and arguments, providing streams for input/output. It’s ideal for handling large outputs or long-running processes.

JavaScript
const { spawn } = require('child_process'); const child = spawn('ls', ['-lh', '/usr']);  child.stdout.on('data', (data) => {     console.log(`stdout: ${data}`); });  child.stderr.on('data', (data) => {     console.error(`stderr: ${data}`); });  child.on('close', (code) => {     console.log(`child process exited with code ${code}`); }); 

Output

Child-Process

Node child Process

In this example

  • spawn(‘ls’, [‘-lh’, ‘/usr’]): Executes the ls command with -lh and /usr as arguments.
  • child.stdout.on(‘data’, …): Listens for data from the standard output.
  • child.stderr.on(‘data’, …): Listens for data from the standard error.
  • child.on(‘close’, …): Listens for the close event, indicating the process has finished.

2. fork() method

The fork() method is a special case of spawn() used specifically for spawning new NodeJS processes. It establishes an IPC (Inter-Process Communication) channel between the parent and child processes, allowing them to communicate via message passing.

JavaScript
const { fork } = require('child_process');  const child = fork('child.js');  child.on('message', (message) => {   console.log(`Message from child: ${message}`); });  child.send('Hello from parent'); 
JavaScript
// Child.js  // Listen for messages from the parent process process.on('message', (message) => {   console.log(`Message from parent: ${message}`);    // Send a response back to the parent   process.send('Hello from child'); }); 

Output

Fork-methode

Fork methode

In this example

  • fork(‘child.js’): Spawns a new NodeJS process running the child.js module.
  • child.on(‘message’, …): Listens for messages from the child process.
  • child.send(‘Hello from parent’): Sends a message to the child process.

3. exec() method

The exec() method runs a command in a shell and buffers the output, which is suitable for short-lived commands with small outputs.

JavaScript
const { exec } = require('child_process');  // Counts the number of directory in // current working directory exec('dir | find /c /v ""', (error, stdout, stderr) => {     if (error) {         console.error(`exec error: ${error}`);         return;     }     console.log(`stdout: No. of directories = ${stdout}`);     if (stderr != "")         console.error(`stderr: ${stderr}`); }); 
JavaScript
// child_process const child = spawn('cmd', ['/c', 'dir']); 

Output

Execute-method

exec methdo

In this example

  • exec(‘ls -lh /usr’, …): Executes the ls command with -lh and /usr as arguments.
  • The callback receives error, stdout, and stderr as parameters.
  • Logs the standard output and error to the console.

4. execFile() method

The execFile() method runs an executable file directly without spawning a shell, making it more efficient than exec() for running binaries and scripts directly.

JavaScript
const { execFile } = require('child_process');  execFile('node', ['--version'], (error, stdout, stderr) => {     if (error) {         console.error(`execFile error: ${error}`);         return;     }     console.log(`stdout: ${stdout}`);     if (stderr) {         console.error(`stderr: ${stderr}`);     } }); 
  • execFile(‘node’, [‘–version’], …): Executes the NodeJS binary with the –version flag.
  • The callback receives error, stdout, and stderr as parameters.
  • Logs the standard output and error to the console.

Comparison of exec, execFile, spawn, and fork

Method

Use Shell?

Returns Output

Streaming

Use Cases

exec()

Yes

Buffers output

No

Small shell commands

execFile()

No

Buffers output

No

Running binary files

spawn()

Yes

No (streams instead)

Yes

Handling large outputs

fork()

No

Uses message passing

Yes

Running child NodeJS processes

Best Practices for Using Child Processes

  • Use exec() for simple shell commands (when output size is small).
  • Use execFile() for executing binary files (faster & safer).
  • Use spawn() for handling large data or real-time output streaming.
  • Use fork() for multi-processing and parallel execution in NodeJS.
  • Always handle errors properly (use stderr and error events).
  • Use asynchronous methods whenever possible to avoid blocking the event loop.


Next Article
Node.js process.kill() Method

S

Shreyasi_Chakraborty
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Node.js-Basics

Similar Reads

  • Node process.cwd() Method
    The process.cwd() method is an inbuilt application programming interface of the process module which is used to get the current working directory of the node.js process. Syntax: process.cwd()Parameters: This method does not accept any parameters. Return Value: This method returns a string specifying
    2 min read
  • Node.js process.chdir() Method
    The process.chdir() method is an inbuilt application programming interface of the process module which is used to change the current working directory. Syntax: process.chdir( directory ) Parameters: This method accepts single parameter as mentioned above and described below: directory: It is require
    2 min read
  • Node.js process.kill() Method
    The process.kill( pid[,signal] ) is an inbuilt method of node.js which sends a signal to the process, pid (which is the process id) and signal is in the string format that is the signal to send. Syntax : process.kill(pid[, signal]) Parameters: This method accepts two parameters as mentioned above an
    2 min read
  • Node.js process.hrtime( ) Method
    The process.hrtime() method to measure code execution time which returns an array that includes current high-resolution real-time in [seconds, nanoseconds]. We measure the code execution time by providing the time returned by the first process.hrtime() call as a parameter in the second process.hrtim
    3 min read
  • Node.js process.send() Method
    The process.send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process. This method does not work for the root process because it does not have any parent process. Syntax: process.send(message, [sendHa
    2 min read
  • Node.js process.exit() Method
    The process.exit() method is used to end the process which is running at the same time with an exit code in NodeJS. Syntax: process.exit( code ) Parameter:  This function accepts single parameter as mentioned above and described below: Code: It can be either 0 or 1. 0 means end the process without a
    2 min read
  • Node.js process Object
    A process object is a global object, so it can be accessed from anywhere. As it is a predefined library, so we don't have to download it to our system globally. Prerequisites: Basic knowledge of  NodeNode.js installed (version 12+)NPM installed (version 6+)Requiring Module: You can include the modul
    2 min read
  • Node.js process.cpuUsage() Method
    The process.cpuUsage() method is an inbuilt application programming interface of the Process module which is used to get the user, system CPU time usage of the current process. It is returned as an object with property user and system, values are in microseconds. Return values may differ from the ac
    2 min read
  • Node.js process.abort() Method
    The process.abort() property is an inbuilt application programming interface of the process module which is used to abort a running NodeJS process immediately. It also generates a core file. Syntax: process.abort() Parameter: This function does not accept any parameter. Return Type: It has a void re
    2 min read
  • Node.js Projects
    Node.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences