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
How to Run Node.js Program as an Executable ?
Node.js allows you to create standalone executables from your JavaScript programs, making them easy to distribute and run on various platforms without requiring Node.js to be installed. This article will guide you through the process of converting a Node.js program into an executable file using popu
2 min read
How to Exit Process in Node.js ?
In this article, we will see how to exit in NodeJS application. There are different types of methods to exit in Nodejs application, here we have discussed the following four methods. Table of Content Using ctrl+C keyUsing process.exit() FunctionUsing process.exitCode variableUsing process.on() Funct
3 min read
How to use External Modules and NPM in a project ?
Need for External Modules: For a large JavaScript application, it becomes difficult and messy to write the whole code in just one JavaScript file. This is where CommonJS comes into the picture and this CommonJS format defines a module format that can be used up for breaking your JS application into
3 min read
How to run a node.js application permanently ?
NodeJS is a runtime environment on a V8 engine for executing JavaScript code with some additional functionality that allows the development of fast and scalable web applications but we can't run the Node.js application locally after closing the terminal or Application, to run the nodeJS application
2 min read
Node.js process.execPath Property
The process.execPath property is an inbuilt application programming interface of the process module which is used to get the absolute pathname of the node.js executable which started the node.js process.Syntax:Â Â process.execPath Return Value: This property returns a string signifies the absolute pa
1 min read
How to Create and Run a Node.js Project in VS Code Editor ?
Visual Studio Code (VS Code) is a powerful and user-friendly code editor that is widely used for web development. It comes with features like syntax highlighting, code suggestions, and extensions that make coding easier. In this article, we'll show you how to quickly create and run a Node.js project
2 min read
How to Build a Simple Web Server with Node.js ?
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
Node.js Process warning Event
The 'warning' is an event of class Process within the process module which is emitted whenever Node.js emits a process warning. Syntax: Event: 'warning'Parameters: This event does not accept any argument as a parameter. Return Value: This event returns nothing but a callback function for further ope
2 min read
Node.js process.report.getReport([err]) Function
The process.report.gerReport() is a method of process.report javascript object that helps generate a report of the currently running node.js process. Syntax: process.report.getReport([err]) Parameters: It takes an array of Error Object that represents a custom error in the javascript stack Return Va
1 min read
How to Run Node.js with Express on Mobile Devices ?
Node.js is a cross-platform open-source Javascript runtime environment and library for running web applications outside the browser. It is based on Chrome's V8 engine. Node.js is used to create server-side and command-line applications. Express.js is one of the most popular node frameworks. It is a
2 min read