Skip to content

Instantly share code, notes, and snippets.

@axiak
Created April 21, 2012 02:15
Show Gist options
  • Save axiak/2433287 to your computer and use it in GitHub Desktop.
Save axiak/2433287 to your computer and use it in GitHub Desktop.
var exec = require('child_process').exec
, fs = require('fs');
var escapeShell = function(cmd) {
return '"'+cmd.replace(/(["\s'$`\\])/g,'\\$1')+'"';
};
var runCommand = function (processTmpl, inputFile, outputFile, callback) {
var useStdin = true, useStdout = true;
if (processTmpl.search("{input}") !== -1) {
processTmpl = processTmpl.replace("{input}", escapeShell(inputFile));
useStdin = false;
}
if (processTmpl.search("{output}") !== -1) {
processTmpl = processTmpl.replace("{output}", escapeShell(outputFile));
useStdout = false;
}
var stdoutStream;
if (useStdout) {
stdoutStream = fs.createWriteStream(outputFile);
}
var subProcess = exec(processTmpl);
subProcess.stderr.pipe(process.stderr);
if (stdoutStream) {
subProcess.stdout.pipe(stdoutStream);
}
subProcess.stdout.on('exit', function (code) {
if (code) {
callback("Command '" + processTmpl + "' failed with status code " + code);
} else {
if (stdoutStream) {
stdoutStream.end();
fs.close(fd, function () {
callback();
});
} else {
callback();
}
}
});
if (useStdin) {
var inputStream = fs.createReadStream(inputFile);
inputStream.pipe(subProcess.stdin);
inputStream.on('error', function (exc) {
subProcess.kill();
callback("Error reading file '" + inputFile + "': " + exc);
});
}
};
runCommand("python y.py", "/tmp/testin", "/tmp/testout", function (err) {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment