节点 - 将变量传递给子进程

node - pass variable to child process

是否可以将变量传递给节点 cli 脚本的子进程? 例如:

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

您可以传递字符串值或任何可以转换为字符串的内容作为命令行参数。

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

child_process.spawn() 的第二个参数可以是一个字符串数组,将作为命令行参数传递给新进程。新进程的代码,然后需要从命令行获取它们才能使用它们。

请注意,参数必须是字符串或具有 .toString() 方法的东西,可以将其转换为有意义的字符串。

另请注意 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.