Created
May 9, 2014 20:39
-
-
Save amoilanen/20ee20b7a40995b1836c to your computer and use it in GitHub Desktop.
Running command from Node.js by spawning a new process
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
var spawn = require('child_process').spawn; | |
function spawnProcess(dir, cmd) { | |
return (process.platform.toLowerCase().indexOf("win") >= 0) | |
? spawnWindowsProcess(dir, cmd) | |
: spawnLinuxProcess(dir, cmd); | |
} | |
function spawnWindowsProcess(dir, cmd) { | |
return spawn("cmd.exe", ["/c", cmd], {cwd: dir}); | |
} | |
function spawnLinuxProcess(dir, cmd) { | |
var cmdParts = cmd.split(/\s+/); | |
return spawn(cmdParts[0], cmdParts.slice(1), { cwd: dir}); | |
} | |
function runCmdHandler(dir, cmd) { | |
var process = null; | |
try { | |
process = spawnProcess(dir, cmd); | |
} catch (e) { | |
console.error("Error trying to execute command '" + cmd + "' in directory '" + dir + "'"); | |
console.error(e); | |
console.log("error", e.message); | |
console.log("finished"); | |
return; | |
} | |
process.stdout.on('data', function (data) { | |
console.log("progress", data.toString('utf-8')); | |
}); | |
process.stderr.on('data', function (data) { | |
console.log("error", data.toString('utf-8')); | |
}); | |
process.on('exit', function (code) { | |
console.log("finished"); | |
}); | |
} | |
/* | |
* Example commands. | |
*/ | |
runCmdHandler(".", "find . -name '*.js'"); | |
runCmdHandler(".", "uname -a"); | |
runCmdHandler(".", "ls -lh ."); | |
runCmdHandler("/home/anton/src/github/grunt-prepr", "grunt"); | |
runCmdHandler(".", "git clone https://github.com/antivanov/Brackets-Command-Line-Shortcuts"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't know for the windows part but for Unix like system, line https://gist.github.com/antivanov/20ee20b7a40995b1836c#file-running-command-node-js-L14 will split command arguments on any space chars encountered therefore your error
Please note also that the embedded double-quotes might also lead to further misbehaviours
one easy but dirty way would be to try something like
runCmdHandler(".", "ffmpeg -y -f dshow -i video=\x22Webcam\x20C170\x22 -codec:v libx264 -qp 0 -t 0:00:05 createvideo.mp4");