Spawning a Process in Another Node.js Instance Using spawn()

A rather complex method of adding work to another process from a Node.js process is to spawn another process; link the stdio, stdout, and stderr pipes between them; and then execute a file on the new process, using the spawn() function. This method is a bit heavier than simply using exec() but provides some great benefits.

The major difference between spawn() and exec()/execFile() is that stdin for the spawned process can be configured, and stdout and stderr are Readable streams in the parent process. This means exec() and execFile() must complete before you can read the buffer outputs. However, you can read output data from a spawn() process as soon as it has been written.

The syntax for the spawn() function, which returns a ChildProcess object, is shown below:

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

The command parameter is a string that specifies the command that is executed. The args parameter is an array that specifies command-line arguments to be passed to the executable command. The options parameter is an object that specifies settings to use when executing the command, such as the current working directory. Table 9.8 lists the options you can specify with the spawn() command.

Image

Table 9.8 Options that can be set with the spawn() function

The callback parameter is a function that accepts three parameters: error, stdout, and stderr. The error parameter is passed an error object if an error is encountered during execution of the command. stdout and stderr are defined by the stdio option settings; by default they are Readable stream objects.

Listing 9.4 is an example of executing a system command using the spawn() function. Figure 9.4 shows the output of Listing 9.4.

Listing 9.4 child_process_spawn.js: Spawning a command in another process


01 var spawn = require('child_process').spawn;
02 var options = {
03     env: {user:'brad'},
04     detached:false,
05     stdio: ['pipe','pipe','pipe']
06 };
07 var child = spawn('netstat', ['-e']);
08 child.stdout.on('data', function(data) {
09   console.log(data.toString());
10 });
11 child.stderr.on('data', function(data) {
12   console.log(data.toString());
13 });
14 child.on('exit', function(code) {
15   console.log('Child exited with code', code);
16 });


Image

Figure 9.4 Output streamed from a spawned command using spawn().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.105.255