Skip to content Skip to sidebar Skip to footer

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, i

Solution 1:

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

varPromise = require('bluebird')
var exec   = require('child_process').exec// Array with input/output pairsvar data = [
  ['input1', 'output1'],
  ['input2', 'output2'],
  ...
]

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

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

Post a Comment for "Nodejs Handling Multiple Subprocess Together"