简体   繁体   中英

node - pass variable to child process

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 });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM