Created
December 6, 2016 04:34
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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