Skip to content

Instantly share code, notes, and snippets.

@mykyta-shulipa
Forked from millermedeiros/example.js
Last active December 3, 2015 22:48
Show Gist options
  • Save mykyta-shulipa/4fdcc8bb6f5b66bc6ec1 to your computer and use it in GitHub Desktop.
Save mykyta-shulipa/4fdcc8bb6f5b66bc6ec1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// USAGE ------
// ============
var shell = require('./shellHelper');
// execute a single shell command
shell.exec('npm test --coverage', function(err){
console.log('executed test');
}});
// execute multiple commands in series
shell.series([
'node build release',
'git add -A',
'git commit --verbose'
], function(err){
if (err) {
console.log('executed many commands in a row');
}
});
// spawn a child process and execute shell command
// borrowed from https://github.com/mout/mout/ build script
// author Miller Medeiros
// released under MIT License
// version: 0.1.0 (2013/02/01)
// execute a single shell command where "cmd" is a string
exports.exec = function(cmd, cb){
// this would be way easier on a shell/bash script :P
var child_process = require('child_process');
var parts = cmd.split(/\s+/g);
var p = child_process.spawn(parts[0], parts.slice(1), { cwd: process.cwd(), stdio: 'inherit' });
p.stdout.setEncoding('utf8');
p.stdout.on('data', function (data) {
console.log(data);
});
p.stderr.setEncoding('utf8');
p.stderr.on('data', function (data) {
console.log(data);
});
p.on('exit', function(code){
var err = null;
if (code) {
err = new Error('command "'+ cmd +'" exited with wrong status code "'+ code +'"');
err.code = code;
err.cmd = cmd;
}
if (cb) cb(err);
});
};
// execute multiple commands in series
// this could be replaced by any flow control lib
exports.series = function(cmds, cb){
var execNext = function(){
exports.exec(cmds.shift(), function(err){
if (err) {
cb(err);
} else {
if (cmds.length) execNext();
else cb();
}
});
};
execNext();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment