0

I have an array and i want to send it to a child process. But the problem is i get it in child process as a string. How can i fix it? Thanks.

parent file

const {fork} = require('child_process');

var botsList = [];
fork('./app.js', [botsList]);

child file:

var botsList = process.argv[2];
console.log(typeof botsList); 
1
  • Args are always strings, you need to parse it. Commented May 16, 2020 at 12:12

1 Answer 1

1

app.js will receive a string, but depending on the complexity of botsList, you could use JSON.stringify and JSON.parse

index.js will do something like:

const {fork} = require('child_process');                                                                                                                                                                

var botsList = ["botA", "botB", "botC"];

fork('./app.js', [JSON.stringify(botsList)]);

And app.js will do parsing of the argument:

let botsList = process.argv[2];                                                                                                                                                                         

try {                                                                                                       
     botsList = JSON.parse(botsList);                                                            
} catch (e) {                                                                                               
     console.log('Could not parse string as JSON');                                              
}                                                                                                                                                                                                       

console.log(botsList);                                                                              
console.log(typeof botsList);   

And the output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.