Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Created May 9, 2014 20:39
Show Gist options
  • Save amoilanen/20ee20b7a40995b1836c to your computer and use it in GitHub Desktop.
Save amoilanen/20ee20b7a40995b1836c to your computer and use it in GitHub Desktop.
Running command from Node.js by spawning a new process
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");
@dellwatson
Copy link

the template with space inside "cmd" somehow unable to read ?
eg:
what i run in my cmd is : ffmpeg -y -f dshow -i video="Webcam C170" -codec:v libx264 -qp 0 -t 0:00:05 createvideo.mp4

so it's goin to be:
runCmdHandler(".", "ffmpeg -y -f dshow -i video="+"Webcam C170"+" -codec:v libx264 -qp 0 -t 0:00:05 createvideo.mp4");

somehow it only write Webcam through nodejs, while it perfectly fine when i do manually in cmd line?
do u have any idea please ?

@obourdon
Copy link

obourdon commented Jan 7, 2018

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");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment