The simplest way to add work to another process from a Node.js process is to execute a system command in a subshell, using the exec()
function. The exec()
function can execute just about anything that can be executed from a console prompt, such as a binary executable, shell script, Python script, or batch file.
When executed, the exec()
function creates a system subshell and then executes a command string in that shell just as if you had executed it from a console prompt. This gives you the advantage of being able to leverage the capabilities of a console shell, such as accessing environment variables, on the command line.
The syntax for the exec()
function, which returns a ChildProcess
object, is shown below:
child_process.exec(command, [options], callback)
The command
parameter is a string that specifies the command to execute in the subshell. The options
parameter is an object that specifies settings to use when executing the command, such as the current working directory. Table 9.7 lists the options you can specify with the exec()
and execFile()
commands.
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 Buffer
objects that contain the output from executing the command.
Listing 9.2 shows an example of executing a system command using the exec()
function. Figure 9.2 shows the output of Listing 9.2.
01 var childProcess = require('child_process'),
02 var options = {maxBuffer:100*1024, encoding:'utf8', timeout:5000};
03 var child = childProcess.exec('dir /B', options,
04 function (error, stdout, stderr) {
05 if (error) {
06 console.log(error.stack);
07 console.log('Error Code: '+error.code);
08 console.log('Error Signal: '+error.signal);
09 }
10 console.log('Results:
' + stdout);
11 if (stderr.length){
12 console.log('Errors: ' + stderr);
13 }
14 });
15 child.on('exit', function (code) {
16 console.log('Completed with code: '+code);
17 });