【发布时间】:2020-03-07 09:38:26
【问题描述】:
我试图在 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:节点:没有这样的文件或目录重要提示:我不希望任何值从这个特定脚本中泄漏出来,这就是为什么我试图避免使用 export FOO=bar 语法,但我可能误解了它的工作原理。
我更喜欢使用shelljs 的解决方案,但我愿意接受使用child_process.exec、execa 等的其他解决方案。
【问题讨论】:
标签: node.js shell environment-variables