0

Is possible to pass a variable to a child process of a node cli script? For example:

const child = require('child_process').spawn;
const script = 'path/to/my/file.js';

const a = 'value';
// pass the variable a to child
child('node', [script], { cwd: __dirname });
newbiedev
  • 2,607
  • 3
  • 17
  • 65

1 Answers1

1

You can pass string values or anything that can be converted into a string as command line arguments.

const child = require('child_process').spawn;
const script = 'path/to/my/file.js';

const a = 'value';
// pass the variable a to child
child('node', [script, a], { cwd: __dirname });

The second argument to child_process.spawn() can be an array of strings that will be passed as command line arguments to the new process. The code for the new process, then needs to get them from the command line to use them.

Note, the arguments must be strings or something that has a .toString() method that will convert it into a meaningful string.

Also note this safety comment in the doc:

If the shell option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I've read the documentation about and that part was not really clear for me. Thank you for the explaination. I see from the snippet that you have passed two array, one is the script that will be executed and the second for the variable I want to pass. I can also pass the variable inside the script array?How I will get it inside the child process script? – newbiedev Mar 17 '21 at 17:40
  • 1
    @newbiedev - The two array was a mistake. It should just be two items in one array. I was confused about what you were doing with your original code. Anyway, I corrected the answer. The way it shows now, it will be equivalent to typing this on the cmd line: `node path/to/my/file.js value` which is what I think you want. `node` create the `process.argv` from this and that will be available to your script. – jfriend00 Mar 17 '21 at 17:47