Open In App

How can We Run an External Process with Node.js ?

Last Updated : 24 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:



Next Article

Similar Reads