我正在尝试在Node.js脚本中生成特定值,然后将它们作为环境变量传递给Shell命令,但是我似乎无法使其正常工作。在传入我自己的环境变量的同时从Node.js作为shell命令执行字符串的正确方法是什么?
以下内容似乎不符合我的预期:
const shell = require("shelljs");
const { findPort } = require("./find-port");
async function main() {
// imagine that `findPort(value)` starts at the provided `value` and
// increments it until it finds an available port
const PORT = await findPort(8000); // 8000,8001,etc
const DB_PORT = await findPort(3306); // 3306,3307,etc
shell.exec(`yarn run dev`,{
env: {
PORT,DB_PORT,},async: true,});
}
main();
当我尝试运行此命令时,出现以下错误:
env: node: No such file or directory
重要:我不希望任何值从该特定脚本中泄漏出来,这就是为什么我试图避免使用export FOO=bar
语法的原因,但是我可能会误解它的工作原理。
我更喜欢使用shelljs
的解决方案,但是我对使用child_process.exec
,execa
等的其他解决方案持开放态度。