gpt4 book ai didi

Node.js:如何使用 shell 命令传递环境变量?

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:05 28 4
gpt4 key购买 nike

我试图在 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.execexeca 的其他解决方案持开放态度,等等

最佳答案

该脚本完全按照您的要求进行:它使用您的环境变量运行yarn run dev。不幸的是,这意味着它使用yarn依赖的系统环境变量(例如PATH)运行。

您可以使用您的变量和系统变量来运行它:

  shell.exec(`yarn run dev`, {
env: {
...process.env,
PORT,
DB_PORT,
}
});

关于Node.js:如何使用 shell 命令传递环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805784/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com