simple exec sync in nodejs
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 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