Created
February 11, 2014 01:23
-
-
Save phette23/8927662 to your computer and use it in GitHub Desktop.
This file contains 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
// 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