Open In App

What is spawn in Node JS ?

Node JS is a cross-platform, open-source back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of an internet browser. In this article, we will learn about the Spawn in NodeJs.

Prerequisites

Spawn is a technique furnished by using the child_process module in Node.Js. It is used to spawn new approaches, allowing Node.Js programs to execute external instructions or different scripts as separate techniques. The spawn function creates a new baby manner asynchronously, offering admission to to the input/output streams for reading and writing information. This feature takes in the command to be carried out alongside an array of arguments and extra alternatives as parameters.



Syntax:

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

The following is the description of the parameters used in the function:



Example 1: In this example, I am using spawn to run a child process that lists all the files and sub-directories in the current working directory.




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

Output:

Example 2: In this example, I am running a python child process that prints the Hello World message on the stdout stream.




import { spawn } from 'child_process';
 
const pythonProcess = spawn('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}`);
})

Output:

Reference: https://nodejs.org/api/child_process.html#child_processspawncommand-args-options


Article Tags :