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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With