How can i pass argument to child_process.exec callback
Asked Answered
R

2

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

Richie answered 12/4, 2013 at 12:36 Comment(1)
I've found a way to pass additional parameters to any function (specifically an anonymous one). I posted that answer here: https://mcmap.net/q/93634/-pass-additional-parameter-to-javascript-callback-function-duplicateSelfinsurance
M
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
}
Mariannemariano answered 12/4, 2013 at 12:52 Comment(2)
well, when i try your solution like that pastebin.com/mxxji4HS , it doesn't workRichie
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. github.com/caolan/async#each or github.com/caolan/async#eachSeriesMariannemariano
R
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!

Richie answered 12/4, 2013 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.