Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute command line argument in Node.js with existing global variables?

I'm executing something in the command line like so:

var exec = require('child_process').exec;
var cmd = 'some command';

exec(cmd, function(error, stdout, stderr) {
  console.log(error);
  console.log(stdout);
  console.log(stderr);
});

It work's fine, but it doesn't seem to have the parents scope. For instance I have a $app global variable that is available in the calling function.

But in the 'some command' I run it is not available. Is there any way to pass this in? Basically I wanna have access to $app in my child command line command.

like image 936
Rob Avatar asked Jan 31 '26 02:01

Rob


1 Answers

passing parameters:

You should be able to do something like:

var options = {
    env : process.env
}

exec(cmd, options, function (error, stdout, stderr) {
    //...
});

This will give you access to all the environment variables from the parent.

Even if the environment variable is not set you can create one in the parent node program on the fly, e.g.:

// in parent program before calling exec.
process.env.userInputtedName = "Joe";

The child now has access to that environment variable.

See child_process.exec documentation

passing objects:

If is an object you wish to pass an object from the parent to the child you can used JSON functions to encode and decode , e.g.

process.env.details = JSON.stringify({
   custom : 'object',
   containing : [ 'complex', 'structures' ] 
});
var options = {
    env : process.env
};

Then decode the JSON in your child program (e.g. for JS):

var importedObject = JSON.parse(process.env.details);

For more involved inter-process communications you might want to look at a network library such as net or zeroMQ.

like image 138
chriskelly Avatar answered Feb 01 '26 14:02

chriskelly