Reputation: 4776
I am running a script inside a script using child_process.fork()
. I am using a variable (an instance of another application) inside my main script and I need to pass this as an argument to the subsequent script to get it updated there. I tried it following way
Sub script
console.log(process.data);
let a = process.data;
.....................
Main script
function runScript(scriptPath, data, callback) {
var invoked = false;
var process = childProcess.fork(scriptPath, data);
process.on('error', function (err) {
if (invoked) return;
invoked = true;
callback(err);
});
process.on('exit', function (code) {
if (invoked) return;
invoked = true;
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
}
let dataValues = "this from the main script";
runScript('./subscript.js' ,dataValues, function (err) {
if (err) throw err;
console.log('finished running some-script.js');
});
I am getting undefined
when I try to access the argument from the subsequent script. Seems like the argument is not sent to the subsequent script. It was running as expected if I don't pass arguments to the second script.
What is the issue with the way of my data sending to the subsequent script?
Upvotes: 0
Views: 502
Reputation: 9907
.fork(...)
expects a string[]
, not astring
(docs), so try passing the arguments as an array:
let dataValues = ["this from the main script"];
Also, in the child process, you will receive the arguments in the process.argv
array, not process.data
. Try this for in child process script:
console.log(process.argv);
Upvotes: 1
Reputation: 2528
You can send args as command line arguments to your second script like
childProcess.fork(scriptPath+" "+data); //data can be a1 a2 a3
and then on your script (scriptPath) you can access them by process.argv
for (let j = 0; j < process.argv.length; j++) {
console.log(j + ' -> ' + (process.argv[j]));
}
// output will be
0 -> a1
1 -> a2
2 -> a3
Upvotes: 0