Executing an Executable File on Another Process Using execFile()

A simple way to add work to another process from a Node.js process is to execute an executable file on another process using the execFile() function. This is very similar to exec() except that there is no subshell used. This makes execFile() lighter weight, but it also means that the command to execute must be a binary executable. Shell scripts on Linux and batch files on Windows do not work with the execFile() function.

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

child_process.execFile(file, args, options, callback)

The file parameter is a string that specifies the path to the executable file that is executed. The args parameter is an array that specifies command-line arguments to be passed to the executable. 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 execFile() 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 buffer objects that contain the output from executing the command.

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

Listing 9.3 child_process_exec_file.js: Executing an executable file in another process


01 var childProcess = require('child_process'),
02 var options = {maxBuffer:100*1024, encoding:'utf8', timeout:5000};
03 var child = childProcess.execFile('ping.exe', ['-n', '1', 'google.com'],
04                             options, 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('Child completed with code: '+code);
17 });


Image

Figure 9.3 Output from executing an executable file using execFile().

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

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