Thoughts

Execute Command Using NodeJs

Javascript NodeJs

Occasionally you may want to execute a command from a Node.js script. I recently ran into a scenario where I wanted to run MSBuild from a Gulp.js build. Below is a small snippet demonstrating how to execute a command from a Node.js script using child_process.exec:


/* Execute Command using child_process.exec */

var exec = require('child_process').exec;
var child;

child = exec('msbuild', function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

Exec is useful for short running processes that execute and terminate without returning alot of data.

There is also another method for executing commands — child_process.spawn. With exec output is buffered, meaning output is returned at one time when the process has executed. With spawn output is streamed, meaning output is returned immediately. Spawn is useful for longer running processes or processes that return lots of data. Below is an example of how to use spawn:


/* Execute Command using child_process.spawn */

var spawn = require('child_process').spawn;
var child = spawn('msbuild', []);

child.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});

child.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

child.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

Disclaimer: The opinions expressed here are my own personal opinions and do not represent my employer's view in any way.