nodejs一起处理多个子流程 [英] nodejs handling multiple subprocess together

查看:79
本文介绍了nodejs一起处理多个子流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的情况,我需要创建n个子流程,对于每个子流程,我需要提供stdin数据和预期的输出,如果预期的输出与所产生的输出相同,则该子流程的结果是成功的.如果所有此类子过程均成功,则需要将状态发送给用户.如何在nodejs中以非阻塞方式进行上述操作?

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?

推荐答案

承诺!

我个人使用了Bluebird,这也是一个使用它的示例.希望您能理解,什么时候不要问:-)

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
})

这篇关于nodejs一起处理多个子流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆