简体   繁体   English

nodejs一起处理多个子流程

[英]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. 我遇到一种情况,我需要创建n个子流程,对于每个子流程,我需要提供stdin数据和预期输出,如果预期输出与所产生的输出相同,则子流程的结果为成功。 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? 如何以非阻塞方式在nodejs中执行上述操作?

Promises! 答应!

I personally use Bluebird, and here is an example that uses it too. 我个人使用了Bluebird,这也是一个使用它的示例。 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
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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