Skip to content

Instantly share code, notes, and snippets.

@ChristianRich
Created December 6, 2016 04:34
Show Gist options
  • Save ChristianRich/db2932c1b83dcc1c71c377ef02540035 to your computer and use it in GitHub Desktop.
Save ChristianRich/db2932c1b83dcc1c71c377ef02540035 to your computer and use it in GitHub Desktop.
Makes it possible to run shell commands from a Node script. Tested on Mac and Windows. Inspired by https://gist.github.com/goatslacker/1050077
#!/usr/bin/env node
const exec = require('child_process').exec
, Promise = require('promise');
/**
* @param {Array} array of shell commands
*/
module.exports = function(array){
return new Promise(function(resolve, reject){
if(!array || !array.length){
return resolve();
}
let size = array.length,
curr = 0;
const next = function(cmd){
exec(cmd, function(err, stdout, stderr){
if(err){
console.error(err);
}
if(stdout){
console.log(stdout);
}
if(stderr){
console.log(stderr);
}
if(err){
return reject(err);
}
curr++;
if(curr < size){
cmd = array.shift();
return next(cmd);
}
resolve();
});
};
next(array.shift());
});
};
// Example usage
// -------------
// const exec = require('./exec');
// let commands = [
// 'node -v',
// 'npm -v',
// 'echo "Hello World"'
// ];
// exec(commands)
// .then(function(){
// process.exit(0);
// })
// .catch(function(err){
// process.exit(1);
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment