Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i 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 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

like image 332
vianney Avatar asked Apr 12 '13 12:04

vianney


People also ask

What is the first argument passed to a callback handler?

The first argument of the callback handler should be the error and the second argument can be the result of the operation. While calling the callback function if there is an error we can call it like callback(err) otherwise we can call it like callback(null, result).

What does exec () do in Nodejs?

The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .

What is exec child_process?

exec() method: This method runs a command in a console and buffers the output. child_process. spawn() method: This method launches a new process with a given command. child_process. fork() method: This method is a special case of spawn() method to create child processes.


2 Answers

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
}
like image 66
Noah Avatar answered Oct 26 '22 21:10

Noah


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!

like image 44
vianney Avatar answered Oct 26 '22 21:10

vianney