javascript - How to promisify Node's child_process.exec and child_process.execFile functions with Bluebird? -


i'm using bluebird promise library under node.js, it's great! have question:

if take @ documentation of node's child_process.exec , child_process.execfile can see both of these functions returning childprocess object.

so what's recommended way promisify such functions?

note following works (i promise object):

var promise = require('bluebird'); var execasync = promise.promisify(require('child_process').exec); var execfileasync = promise.promisify(require('child_process').execfile); 

but how can 1 access original return value of original node.js functions? (in these cases need able access returned childprocess objects.)

any suggestion appreciated!

edit:

here example code using return value of child_process.exec function:

var exec = require('child_process').exec; var child = exec('node ./commands/server.js'); child.stdout.on('data', function(data) {     console.log('stdout: ' + data); }); child.stderr.on('data', function(data) {     console.log('stderr: ' + data); }); child.on('close', function(code) {     console.log('closing code: ' + code); }); 

but if use promisified version of exec function ( execasync above ) return value promise, not childprocess object. real problem talking about.

it sounds you'd return 2 things call:

  • the childprocess
  • a promise resolves when childprocess completes

so "the recommended way promisify such functions"? don't.

you're outside convention. promise returning functions expected return promise, , that's it. return object 2 members (the childprocess & promise), that'll confuse people.

i'd suggest calling unpromisified function, , creating promise based off returned childprocess. (maybe wrap helper function)

this way, it's quite explicit next person reads code.

something like:

var promise = require('bluebird'); var exec = require('child_process').execfile;  function promisefromchildprocess(child) {     return new promise(function (resolve, reject) {         child.addlistener("error", reject);         child.addlistener("exit", resolve);     }); }  var child = exec('ls');  promisefromchildprocess(child).then(function (result) {     console.log('promise complete: ' + result); }, function (err) {     console.log('promise rejected: ' + err); });  child.stdout.on('data', function (data) {     console.log('stdout: ' + data); }); child.stderr.on('data', function (data) {     console.log('stderr: ' + data); }); child.on('close', function (code) {     console.log('closing code: ' + code); }); 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -