简体   繁体   中英

nodejs handling multiple subprocess together

I have got a situation where i need to create n number of subpocess, for each subprocess i need to provide stdin data and expected output, the result of the subpocess is success, if the expected output is same as that of output produced. If all such subprocess is success then the status need to be send to user. How to do the above in nodejs in a nonblocking way?

Promises!

I personally use Bluebird, and here is an example that uses it too. I hope you understand it, feel free to ask when you do not :-)

var Promise = require('bluebird')
var exec   = require('child_process').exec

// Array with input/output pairs
var data = [
  ['input1', 'output1'],
  ['input2', 'output2'],
  ...
]

var PROGRAM = 'cat'

Promise.some(data.map(function(v) {
  var input = v[0]
  var output = v[1]

  new Promise(function(yell, cry) {
    // Yes it is ugly, but exec is just saves many lines here
    exec('echo "' + input + '" | ' + PROGRAM, function(err, stdout) {
      if(err) return cry(err)
      yell(stdout)
    })
  }).then(function(out) {
    if(out !== output) throw new Error('Output did not match!')
  })
}), data.length) // Require them all to succeed
.then(function() {
  // Send succes to user
}).catch(function() {
  // Send failure to the user
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM