Open In App

How can we run an external process with Node.js ?

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is a cross-platform, open-source back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of a web browser. Node.js allows developers to utilize JavaScript to create command-line tools and server-side scripting, which involves running scripts on the server before sending the page to the user’s browser.

In this article, we are going to talk about how we can run external processes with Node.js.

The child_process module provides us with the capability to run external processes in Node.js With the help of the child process module, we may use any system command as a “child process” to access Operating System features. The module provides us with four ways to create a child process:

  • spawn
  • fork
  • exec
  • execFile

Let us now see how we can use each one of these to run external processes:

Note: Before running the files please make sure you set “type”: “module” in the package.json file to use the import syntax.

1. Using spawn method: Using the provided command and the command line arguments in args, the spawn() function creates a new 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.

index.js

Javascript




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:

 

2. 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.

parentFile.js

Javascript




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.')


  • childFile.js

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 parentFile.js

Output: 

 

3. Using exec method: The exec function first establishes a shell before running the command.

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.

index.js

Javascript




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:

 

4. Using execFile method: The execFile() method doesn’t create a shell by default. This makes it slightly more efficient than the exec() method.

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

Python3




print("Hello World!")


index.js

Javascript




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:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads