spawn() method

spawn() method is a new process using the given command and the command line arguments in args. The ChildProcess instance implements EventEmitterAPI which enables us to register handlers for events on child objects directly. Some events that can be registered for handling with the ChildProcess are exit, disconnect, error, close, and message. 

Syntax:

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

Parameters:

  • command: Accepts a string which is the command to run.
  • args: List of string arguments. The default value is an empty array.
  • options:
    • shell: Accepts a boolean value. If true, runs the command inside of a shell. The different shells can be specified as a string. The default value is false which implies no shell. By default, spawn() does not create a shell to execute the command hence it is important to pass it as an option while invoking the child process.

Return Value: Returns a ChildProcess object. 

Example: In this example, we will see the use of the spawn() method.

Javascript




const { spawn } =
    require('child_process');
const child =
    spawn(
        'dir', ['D:\Test'],
        { shell: true }
    );
child.stdout.on('data',
    (data) => {
        console.log(`stdout: ${data}`);
    });
 
child.stderr.on('data',
    (data) => {
        console.error(`stderr: ${data}`);
    });
 
child.on('close',
    (code) => {
        console.log(
            `child process exited with code ${code}`
        );
    });


Output:

Node Child Process

Node is a tool that uses JavaScript and has many useful parts to it. Normally, it does work with one thread at a time, which means it can handle tasks without waiting. However, when there’s a lot of work to be done, we use the child_process module to create additional threads. These extra threads can talk to each other using a built-in messaging system.

The following are the four different ways to create a child process in Nodejs:

Table of Content

  • spawn() method
  • fork() method
  • exec() method
  • execFile() method

Above mentioned ways are explained below: 

Similar Reads

spawn() method:

spawn() method is a new process using the given command and the command line arguments in args. The ChildProcess instance implements EventEmitterAPI which enables us to register handlers for events on child objects directly. Some events that can be registered for handling with the ChildProcess are exit, disconnect, error, close, and message....

fork() method:

...

exec() method:

child_process.fork() is a variant of child_process.spawn() allowing communication between parent and child via send(). It facilitates the isolation of compute-heavy tasks from the main event loop, but numerous child processes can impact performance due to each having its own memory....

execFile() method:

...