The Wayback Machine - https://web.archive.org/web/20240909222158/https://www.geeksforgeeks.org/node-js-child-process/
Open In App

Node Child Process

Last Updated : 16 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Node.js child_process module allows you to create and control child processes, enabling you to execute system commands, run scripts, and perform other operations outside the main Node.js process.

Node.js is a runtime environment that uses JavaScript and has many useful features. Normally, it operates with a single thread, using an event-driven, non-blocking model that allows it to handle tasks without waiting. However, when there’s a lot of work to be done, we use the child_process module to create additional sub-processes, not threads. These sub-processes can communicate with each other using a built-in messaging system.

Child Process Module

The child_process module provides several methods to create and control child processes, each serving different purposes depending on the level of control and interaction you need with the spawned process.

  • exec(): Executes a command in a shell and buffers the output.
  • execFile(): Directly executes a file without a shell, which is more efficient than exec() for simple scripts or commands.
  • spawn(): Launches a new process with a given command, providing streams for stdin, stdout, and stderr.
  • fork(): A specialized version of spawn() specifically designed to spawn new Node.js processes and establish a communication channel between the parent and child.

Creating Child Process

The following are the four different ways to create a child process in Nodejs:

spawn() method:

spawn() method is a new process using the given command and the command line arguments in args. The ChildProcess instance implements EventEmitterAPI which enables us to register handlers for events on child objects directly. Some events that can be registered for handling with the ChildProcess are exit, disconnect, error, close, and message.

Syntax:

child_process.spawn(command[, args][, options])

Parameters:

  • command: Accepts a string which is the command to run.
  • args: List of string arguments. The default value is an empty array.
  • options:
    • shell: Accepts a boolean value. If true, runs the command inside of a shell. The different shells can be specified as a string. The default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as an option while invoking the child process.

Return Value: Returns a ChildProcess object.

Example: In this example, we will see the use of the spawn() method.

JavaScript
const { spawn } =
    require('child_process');
const child =
    spawn(
        'dir', ['D:\Test'],
        { shell: true }
    );
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:

fork() method:

child_process.fork() is a variant of child_process.spawn() allowing communication between parent and child via send() . It facilitates the isolation of compute-heavy tasks from the main event loop, but numerous child processes can impact performance due to each having its own memory.

Syntax:

child_process.fork(modulePath[, args][, options])

Parameters:

  • modulePath: Accepts a string that specifies the module to run in the child.
  • args: List of string arguments.
  • options: CWD, detached, env, execPath, and execArgv are some of the available options for this method.

Return Value: Returns a ChildProcess instance.

Example: In this example, we will see the use of f ork() method.

JavaScript
// Write Javascript code here
const cp = require('child_process');

let child = cp.fork(__dirname + '/sub.js');

child.on('message', function (m) {
    console.log('Parent process received:', m);
});

child.send({ hello: 'from parent process' });

child.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});
JavaScript
process.on('message', function (m) {
    console.log('Child process received:', m);
});

process.send({ hello: 'from child process' });

Output:

exec() method:

exec() method in JavaScript is used to test for the match in a string. If there is a match this method returns the first match else it returns NULL.

Syntax:

child_process.exec(command[, options][, callback])

Parameters:

  • command: Accepts a string that specifies the command to run with space-separated arguments.
  • options: Some of the options available are cwd, env, encoding, shell, timeout etc
  • callback: The callback function is called when the process terminates. The arguments to this function are error, stdout, and stderr respectively.

Return Value: Returns an instance of ChildProcess.

Example: In this example, we will see the use of the exec() method.

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}`);
});

Output:

execFile() method:

The child_process.execFile() function is does not spawn a shell by default. It is slightly more efficient than child_process.exec() as the specified executable file is spawned directly as a new process.

Syntax:

child_process.execFile(file[, args][, options][, callback])

Parameters:

  • file: Accepts a string that specifies the name or path of the file to run.
  • args: List of string arguments.
  • options: Some of the options available are cwd, env, encoding, shell, timeout etc
  • callback: The callback function is called when the process terminates. The arguments to this function are error, stdout, and stderr respectively.

Return Value: Returns an instance of ChildProcess.

Example: In this example, we will see the use of the execFile() method.

JavaScript
const { execFile } = require('child_process');

// Executes the exec.js file
const child = execFile('node', ['exec.js'],
    (error, stdout, stderr) => {
        if (error) {
            throw error;
        }
        console.log(stdout);
    });

Output:

Summary

The child_process module in Node.js is a powerful tool for executing system commands, running scripts, and managing parallel processes . Whether you need to run a shell command, execute a file, or manage multiple Node.js instances, the child_process module provides the necessary functions to handle these tasks efficiently, making it a versatile feature for any Node.js application



Next Article

Similar Reads

Run Python script from Node.js using child process spawn() method
Node.js is one of the most adopted web development technologies but it lacks support for machine learning, deep learning and artificial intelligence libraries. Luckily, Python supports all these and many more other features. Django Framework for Python can utilize this functionality of Python and can provide support for building new age web applica
3 min read
How to get the child node index in JavaScript?
The task is to get the index of child elements among other children. Here are a few techniques discussed. Approach 1: Select the child element of the parent element.Select the parent by .parentNode property.Use Array.prototype.indexOf.call(Children_of_parent, current_child) to get the index. Example 1: This example using the approach discussed abov
2 min read
How to handle Child Threads in Node.js ?
Node.js is a single-threaded language and uses the multiple threads in the background for certain tasks as I/O calls but it does not expose child threads to the developer.But node.js gives us ways to work around if we really need to do some work parallelly to our main single thread process.Child Process in Node: The child_process module gives the n
2 min read
Remove all the child elements of a DOM node in JavaScript
Child elements are the nested elements in the HTML and we have to remove them. To remove the elements in HTML we need to use DOM methods. There are so many ways to remove the child elements of a DOM node: Table of Content Using removeChild()Using innerHTML propertyUsing removeChild()In this approach, we are using the HTML DOM removeChild() method,
2 min read
Explain the Concept of Child Processes in Node
Child processes in Node provide a way to execute multiple processes simultaneously, enabling efficient handling of tasks that can benefit from parallel execution. This concept is particularly useful for tasks such as running CPU-intensive computations, performing I/O operations, or executing external applications without blocking the main event loo
2 min read
How to count child element using jQuery ?
It is very simple to count the number of child elements in the HTML file using jQuery. For example: If you have a parent element consisting of many children elements then you can use .length or.children().length method as given below. Syntax: var len=$("#parentID").length; or var count = $("#parentId").children().length; Example 1: <!DOCTYPE htm
1 min read
How to use a not:first-child selector in CSS?
This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element. Syntax: :not( element ) { // CSS property } Example: <!DOCTYPE html> <html> <head> <title>not first child selector</title> <style> h1 { color
1 min read
How to force child div to be 100% of parent div's height without specifying parent's height?
When designing a website, you may want to create a layout where a child div element fills up the height of its parent div element. However, you may not know the exact height of the parent div element and you don't want to specify it. In this article, we will explore different approaches to force a child div element to be 100% of its parent div elem
3 min read
jQuery :nth-last-child() Selector
The jQuery :nth-last-child() selector is used to select all elements that are the nth last child of their parent. The counting of elements starts from the last element. Syntax: :nth-last-child( n | even | odd | formula )Parameters: The :nth-last-child() selector contain parameters which are listed below: n: It holds the child index number of the se
2 min read
jQuery :last-child Selector
It is a jQuery Selector used to select every element that is the last child of its parent. Syntax: $(":last-child")Example 1: Here is the basic example of a last-child selector. C/C++ Code <!DOCTYPE html> <html> <head> <title>jQuery :last-child Selector</title> <script src= "https://ajax.googleapis.com/ajax/lib
1 min read
jQuery :only-child Selector
It is a jQuery Selector used to select every element that is the only child of it's parent i.e only a single child is selected. Syntax: $(":only-child")Example 1: In this example, we are using only-child selector. C/C++ Code <!DOCTYPE html> <html> <head> <title>jQuery :only-child Selector</title> <script src= "
1 min read
jQuery parent > child Selector
It is a jQuery Selector used to select all elements that are the direct child of its parent element. Syntax: ("parent > child")Parameter Values: parent: Using this, the parent element will be selected.child: Using this, the direct child element of the specified parent element will be selected.Example 1: C/C++ Code <!DOCTYPE html> <html
1 min read
jQuery :nth-child() Selector
The jQuery :nth-child() Selector Selects all elements that are the nth-child of their parent elements. Syntax: $("Selector:nth-child( index | even |odd |equation )")Index: Index provided. Index starts fromeven: even number of child elements get selected.odd: odd number of child elements will get selected.equation: select child elements by solving a
1 min read
How to select all children of an element except the last child using CSS?
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes. Syntax: element:not(:last-child) { // CSS Style } Example 1: This example creates a navigation menu separat
2 min read
How to get specific number of child elements using CSS?
The :nth-child() in CSS Selector is used to select only those elements that are the nth child, regardless of type, of its parent. Syntax: : nth-child(arg) { // CSS Property; } where arg is an argument that represents the pattern for matching elements. It can be number, odd, even or linear equation. number: It represents the elements whose position
2 min read
How to remove parent element except its child element using jQuery ?
Given an HTML document and the task is to remove the parent element except for its child element. Approach 1: Use contents() method to select all the direct children, including text and comment nodes for the selected element.Selected elements are stored in a variable.Now, use replaceWith() method to replace the content of parent element by its all
2 min read
p5.js | child() Function
The child() function is used to add the element as a child element to the parent element. This function accepts either a string ID, DOM node, or p5.Element. If this function does not contain any parameters then it returns an array of children DOM nodes. Note: This function uses the p5.dom library. So add the following line in the head section of th
2 min read
Last-child and last-of-type selector in SASS
SASS is also called Syntactically Awesome Stylesheet. It is a programming language that is interpreted into CSS. The Last Child selector is a selector that allows the user to target the last element inside the containing element. This selector is also known as a Structural Pseudo class which means it is used for styling content on the basis of pare
2 min read
How to count all child elements of a particular element using JavaScript ?
Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementC
1 min read
How to communicate from parent component to the child component in Angular 9 ?
Angular makes the communication between components very easy. In this article, we will learn how to communicate from a parent component to the child component. Approach: Let's create two components: parent child In the parent component, declare the property that you want to receive in the child component, say 'ParentId'. While including the child c
2 min read
How to iterate through child elements of a div using jQuery ?
jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element. To loop through the child elements, the jQuery each() method is used as demonstrated in the following example. Example 1: The sample HTML page contains a
3 min read
How to navigate to a parent route from a child route?
In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and this there is no direct link between them but in g
4 min read
How to make container shrink-to-fit child elements as they wrap?
A Flexible Layout must have a parent element having display property set to flex. Direct child elements of the flexible container automatically become flexible items. Approach: The element below represents a flex container with four flex items. <div id="container"> <ul> <li>icecream</li> <li>sandwich</li
2 min read
How to disable mouseout events triggered by child elements?
In this article, we shall discuss how to avoid triggering unwanted "mouseout" events from child elements due to event bubbling. This maneuver can be achieved by listening to the following events instead of "hover", or "mouseover" and "mouseout" events : onmouseenter: This event is triggered when the cursor/pointer moves onto an element. This event
2 min read
How to create a combined child selector in SASS ?
Introduction: Lets first talk about the various types of Combinators available in CSS. Combinator: A combinator is something that explains the relationship between the selectors. A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator. There are four different combinators in CSS:Descendant
2 min read
How to apply css property to a child element using JQuery?
The task is to apply CSS property to a child element using jQuery. To do that, first we select the child element with the help of children() method in jQuery and then apply CSS property to it with the help of css() method in jQuery. Syntax: // Note : children method selects the direct child to parent $(selector).children("selector").css("property-n
2 min read
How to access child's state in React?
In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.createRef() and attached to React elements via the ref attribute. class App extends React.Component { constructor(props) { super(props
2 min read
How to dragleave fired when hovering a child element in HTML 5?
When a div is made draggable and we hover over a div that executes dragenter and dragleave command, we face a problem when there is a child present inside that div which executes the dragleave command as shown below. Example 1: Here when hovered over child color disappears. C/C++ Code <!DOCTYPE html> <html lang="en"> <head
2 min read
How to return true if the parent element contains the child element in JavaScript ?
In JavaScript, children property returns an array of those elements which are children of a given element. In order to check whether the parent element (say x) contains a child element (say y), we can use the children property to get the array of all children of x and then check whether the array obtained contains y. To get the child element of a p
2 min read
How to call base class constructor from child class in TypeScript ?
In this article, we will learn how we can call the base class constructor from the child class. When a class inherits the properties of another class, it is called a child class and the class whose properties are inherited is called the parent class and the whole process is called Inheritance. In Inheritance, the child class acquires the properties
3 min read
three90RightbarBannerImg