Last active
September 19, 2016 10:43
-
-
Save ianpark/1879bb09d7559854f618e53b5adf4703 to your computer and use it in GitHub Desktop.
Run NodeJS child_process.spawn() with Promise
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
// Run spawn as promised | |
function promised_spawn(cmd, args, option) { | |
let deferred = Q.defer(); | |
let watch = child_process.spawn(cmd, args, option); | |
watch.on('error', (error) => { | |
deferred.reject('encountered error ' + error.message); | |
}) | |
.on('exit', (code) => { | |
if (code !== 0) { | |
deferred.reject('exited with code ' + code); | |
} else { | |
deferred.resolve(); | |
} | |
}) | |
.on('close', (code) => { | |
if (code !== 0) { | |
deferred.reject('exited with code ' + code); | |
} else { | |
deferred.resolve(); | |
} | |
}); | |
watch.stdout.on('data', (data) => { | |
// Print to console directly | |
process.stdout.write(data.toString()); | |
}); | |
watch.stderr.on('data', (data) => { | |
process.stdout.write(data.toString()); | |
}); | |
return deferred.promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment