How to pass argument to child_process.exec callback

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 accepts an error, stdout, sterr.

Ultimately, I can have a unix script that takes extra arguments, runs the command and prints the result of the command and args to stdout, but maybe there is a better way to do this

thank

+5
source share
2 answers

You can call another function inside the callback exec

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
}
+5
source

At the end, I have my_exec function:

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!

+1
source

All Articles