nodejs handling multiple subprocess together

2019-09-03 15:32发布

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?

1条回答
够拽才男人
2楼-- · 2019-09-03 15:44

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
})
查看更多
登录 后发表回答