Reputation: 275
I split my tasks into multiple node scripts, "node programs" that will be run individually with node program1.js
, node program2.js
, etc. using Node's child process exec
function in other Node apps.
This way things split up and I can reuse one program in multiple other apps.
It's easy to get data out of a node program like that, you just throw whatever data you want to stdout and have exec
capture it on the other end.
For putting data into a node program, how? This is easy if the data is only simple command line arguments, but how would I put arbitrary data (binary, JSON, whatever) into it (at or close the point where I would call exec
)? Maybe some piping? Example code I'd appreciate.
Upvotes: 0
Views: 410
Reputation: 91789
Use the env
property to pass environment variables to a spawned child process. You can do this in exec()
, but for spawning Node processes it's better to use fork()
, since it creates a new instance of V8, which is what you're doing.
This is how you'd pass an environment variable:
var exec = require('exec');
var child = exec(command, {
env: {
buffer: new Buffer(8),
json: JSON.stringify(json),
string: 'a simple string'
}
}, function(error, stdout, stderr) {
// execution callback
});
And this is how you'd use the variables in your child process:
process.env.buffer
process.env.json
process.env.string
Upvotes: 1