/ src / main-process / spawner.js
spawner.js
 1  const ChildProcess = require('child_process');
 2  
 3  // Spawn a command and invoke the callback when it completes with an error
 4  // and the output from standard out.
 5  //
 6  // * `command`    The underlying OS command {String} to execute.
 7  // * `args` (optional) The {Array} with arguments to be passed to command.
 8  // * `callback` (optional) The {Function} to call after the command has run. It will be invoked with arguments:
 9  //   * `error` (optional) An {Error} object returned by the command, `null` if no error was thrown.
10  //     * `code` Error code returned by the command.
11  //     * `stdout`  The {String} output text generated by the command.
12  //   * `stdout`  The {String} output text generated by the command.
13  exports.spawn = function(command, args, callback) {
14    let error;
15    let spawnedProcess;
16    let stdout = '';
17  
18    try {
19      spawnedProcess = ChildProcess.spawn(command, args);
20    } catch (error) {
21      process.nextTick(() => callback && callback(error, stdout));
22      return;
23    }
24  
25    spawnedProcess.stdout.on('data', data => {
26      stdout += data;
27    });
28    spawnedProcess.on('error', processError => {
29      error = processError;
30    });
31    spawnedProcess.on('close', (code, signal) => {
32      if (!error && code !== 0) {
33        error = new Error(`Command failed: ${signal != null ? signal : code}`);
34      }
35  
36      if (error) {
37        if (error.code == null) error.code = code;
38        if (error.stdout == null) error.stdout = stdout;
39      }
40  
41      callback && callback(error, stdout);
42    });
43  
44    // This is necessary if using Powershell 2 on Windows 7 to get the events to raise
45    // http://stackoverflow.com/questions/9155289/calling-powershell-from-nodejs
46    return spawnedProcess.stdin.end();
47  };