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