Skip to content

Instantly share code, notes, and snippets.

@phette23
Created February 11, 2014 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phette23/8927662 to your computer and use it in GitHub Desktop.
Save phette23/8927662 to your computer and use it in GitHub Desktop.
// stupid Node.js tricks
// accepts JS object literal of commands & their args
// executes each in series, pipes child process output to parent
// e.g. `node hellspawn.js '{"ls": "-al", "pwd": null, "echo": "Hello world!"}'`
var spawn = require('child_process').spawn
, cmds = JSON.parse(process.argv[2])
, cmd
, key
, val;
for (key in cmds) {
if (cmds.hasOwnProperty(key)) {
val = cmds[key];
// spawn's 2nd param is an array so ensure we're passing it one
if (typeof val === 'string' || typeof val === 'number') {
cmd = spawn(key, [val]);
} else if (Array.isArray(val)) {
cmd = spawn(key, val);
} else {
// assume there's no argument
cmd = spawn(key);
}
// pipe child's output to parent
// otherwise it isn't visible on cli
cmd.stdout.pipe(process.stdout);
cmd.stderr.pipe(process.stderr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment