How can We Run an External Process with Node.js ?
Last Updated :
24 Jun, 2024
Running external processes from within a Node.js application is a common task that allows you to execute system commands, scripts, or other applications. Node.js provides several built-in modules for this purpose, including child_process
, which allows you to spawn, fork, and execute processes. This article will explore different methods to run external processes using Node.js, covering their usage and practical examples.
Methods to Run External Processes
Node.js offers multiple methods to run external processes, each suited for different use cases:
exec
: Executes a command in a shell and buffers the output.execFile
: Executes a specified file without a shell.spawn
: Spawns a new process with more control over input/output streams.fork
: Specifically for spawning new Node.js processes.
Note: Before running the files please make sure you set "type": "module" in the package.json file to use the import syntax.
Using spawn method
The spawn
function offers more control over the input/output streams of the spawned process, making it ideal for continuous data exchange between the Node.js process and the child process.
Syntax:
spawn(command[, args][, options])
Example: Now let's look now how we can use the spawn() method to run an external process. In the following example, I am using the spawn() method to list all the files and sub-directories in the current working directory.
JavaScript
// index.js
import { spawn } from 'child_process';
const lsProcess = spawn('ls');
lsProcess.stdout.on('data', data => {
console.log(`stdout:\n${data}`);
})
lsProcess.stderr.on("data", (data) => {
console.log(`stdout: ${data}`);
});
lsProcess.on('exit', code => {
console.log(`Process ended with ${code}`);
})
Steps to run the application: Write the below command in the terminal to run the application:
node index.js
Output:

Using fork method
The fork() method is a special case of the spawn() method which allows the parent and child processes to communicate using the send() method. It allows for the separation of computationally intensive tasks from the main event loop.
Syntax:
fork(modulePath[, args][, options])
Example: Now let's look now how we can use the fork() method to run an external process. I have created two separate processes here, parentFile.js and childFile.js and through the use of the fork() method I am communicating between them.
JavaScript
// parentFile.js
import { fork } from 'child_process';
const child = fork('childFile.js');
child.on('message', (msg) => {
console.log(`From child process: ${msg}`);
})
child.send('This is parent process.')
JavaScript
// childFile.js
process.on('message', (msg) => {
console.log(`From parent process ${msg}`);
})
process.send('Hi from child process');
Steps to run the application: Write the below command in the terminal to run the application:
node parentFile.js
Output:Â

Using exec method
The exec
function from the child_process
module runs a command in a shell and buffers the output, making it suitable for simple commands that don’t require continuous interaction with the process.
Syntax:
exec(command[, options][, callback])
Example: Now let's look now how we can use the exec() method to run an external process. In the following code, I am simply running an echo command.
JavaScript
// index.js
import { exec } from 'child_process';
exec('echo Hi', (err, stdout, stderr) => {
if(err){
console.log(err);
return;
}
console.log(`stdout: ${stdout}`);
})
JavaScript
process.on('message', (msg) => {
console.log(`From parent process ${msg}`);
})
process.send('Hi from child process');
Steps to run the application: Write the below command in the terminal to run the application:
node index.js
Output:

Using execFile method
The execFile
function is similar to exec
but is more efficient for executing files directly, as it does not involve a shell.
Syntax:
execFile(file[, args][, options][, callback])
Example: Now let's look now how we can use execFile() method to run an external process. In the following example, I am running a python file inside a node.js file using the execFile() method. I have created the python file in the same directory as the node.js file. The project structure should be as follows:
geeksforgeeks/
├─ node_modules/
├─ hello.py
├─ index.js
├─ package.json
hello.py
Python
# hello.py
print("Hello World!")
JavaScript
// index.js
import { execFile } from 'child_process';
const pythonProcess = execFile('python3', ['hello.py']);
pythonProcess.stdout.on("data", (data) => {
console.log(`stdout:\n${data}`);
});
pythonProcess.stderr.on("data", (data) => {
console.log(`stdout: ${data}`);
});
pythonProcess.on("exit", (code) => {
console.log(`Process ended with ${code}`);
});
Steps to run the application: Write the below command in the terminal to run the application:
node index.js
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read