6

is there a way to pass extra arguments to the callback function when i use child_process.exec(cmd,callback) ?

According to the documentation, the callback function only receive error,stdout,sterr.

I could eventually have an unix script who gets extra args, runs the command, and outputs result of the command and args to stdout but maybe there is a better way to do this

Thanks

vianney
  • 380
  • 1
  • 4
  • 12
  • I've found a way to pass additional parameters to any function (specifically an anonymous one). I posted that answer here: http://stackoverflow.com/a/28120741/1695680 – ThorSummoner Jan 24 '15 at 00:11

2 Answers2

6

You can call another function inside the exec callback

var exec = require('child_process').exec
function(data, callback) {
  var cmd = 'ls'
  exec(cmd, function (err, stdout, stderr) {
    // call extraArgs with the "data" param and a callback as well
    extraArgs(err, stdout, stderr, data, callback) 
  })
}

function extraArgs(err, stdout, stderr, data, callback) {
  // do something interesting
}
Noah
  • 33,851
  • 5
  • 37
  • 32
  • well, when i try your solution like that http://pastebin.com/mxxji4HS , it doesn't work – vianney Apr 12 '13 at 14:14
  • 1
    ok, note that the exec command is async but your for loop is not, therefore you may run into unexpected behavior. Try using the async.each or async.eachSeries instead. https://github.com/caolan/async#each or https://github.com/caolan/async#eachSeries – Noah Apr 12 '13 at 14:21
1

At the end, i have a function my_exec :

var exec = require('child_process').exec
function my_exec(cmd,data,callback)
{
    exec(cmd,function(err,stdout,stderr){
        callback(err,stdout,stderr,data)
    })
}

thank you!

vianney
  • 380
  • 1
  • 4
  • 12