Run multiple shell commands synchronously in NodeJs

20Jul13

I came across this issue recently, and after some failed Googling realized that nobody had really solved this very well.

Sure, there’s exec-sync(which doesn’t work with node .10 and is no longer maintained) and execSync(which is dangerous and should not be run outside a development environment) but even both of those feel pretty hacky.  So I thought there must be a better way.

Here it is, using only async and child_process.

var async = require(‘async’);

var exec = require(‘child_process’).exec;

function execSync() {

async.series([

execFn(‘git reset –hard HEAD’, ‘/optional/working/dir’),

execFn(‘git pull origin master’, ‘/optional/working/dir’)

]);

}

var execFn = function(cmd, dir) {

return function(cb) {

console.log(‘EXECUTING: ‘ + cmd);

exec(cmd, { cwd: dir }, function() { cb(); });

}

}

Advertisements


5 Responses to “Run multiple shell commands synchronously in NodeJs”

  1. 1 asdsdas

    How do I get the return string of the shell command that got executed?

    • 2 Luke

      I know you commented a while ago, but you should be able to get the stdout by changing the var execFn to

      var execFn = function (cmd, dir) {
      return function (cb) {
      console.log(‘EXECUTING: ‘ + cmd);
      exec(cmd, {
      cwd: dir
      }, function (error, stdout, stderr) {
      console.log(stdout);
      console.log(error);
      console.log(stderr);
      cb();
      });
      }
      }

  2. 3 dana

    for me doesn t work 😦

  3. 4 anonim

    good thinking but this script might return nothing

  4. How do I setup my computer to automatically update folders onto a removable drive upon insertion?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: