Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@iammapping
Created July 17, 2014 04:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iammapping/000015d6653ba5c8b640 to your computer and use it in GitHub Desktop.
Save iammapping/000015d6653ba5c8b640 to your computer and use it in GitHub Desktop.
simple exec sync in nodejs
var fs = require('fs');
var exec = require('child_process').exec;
/**
* execSync
*
* simple version of execSync
* refer to 'shelljs -> exec', https://github.com/arturadib/shelljs/blob/master/src/exec.js
* @param {String} cmd
* @param {Object} option
*/
function execSync(cmd, option) {
var timestamp = new Date().getTime(),
outFile = '/tmp/exec_sync_out_' + timestamp,
errFile = '/tmp/exec_sync_err_' + timestamp,
doneFile = '/tmp/exec_sync_done_' + timestamp,
sleepFile = '/tmp/exec_sync_sleep_' + timestamp;
exec(cmd + ' 2> ' + errFile + ' 1> ' + outFile + '; echo $? > ' + doneFile, option);
// block and wait child process done
while (!fs.existsSync(doneFile)) {
// reduce cpu usage
fs.writeFileSync(sleepFile, 'a');
}
var code = fs.readFileSync(doneFile, {'encoding': 'utf8'}),
stdout = fs.readFileSync(outFile, {'encoding': 'utf8'}),
stderr = fs.readFileSync(errFile, {'encoding': 'utf8'});
fs.unlinkSync(doneFile);
fs.unlinkSync(outFile);
fs.unlinkSync(errFile);
fs.unlinkSync(sleepFile);
return {
code: code ? parseInt(code) : 0,
stdout: stdout,
stderr: stderr
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment