在多个节点js文件之间共享process.env变量

问题描述 投票:0回答:1

我有两个节点js文件和一个bat文件。在第一个 js 文件中,我设置了一些环境变量,在另一个 js 文件中,我想访问它。但是,设置变量后,我无法在另一个文件中找到这些变量。 例如,

文件1.js

process.env.dev_url=example.com

file2.js

console.log(process.env.user); // This returns correct value as [email protected]
console.log(process.env.dev_url); // returns undefined.

跑步者.bat

ECHO on
SET [email protected]
node file1.js
node file2.js

运行runner.bat后,我可以获取file2中变量

user
的值,但不能获取file1.js中设置的其他变量,可能是什么原因,如何获取file2中的这些值?

javascript node.js environment-variables
1个回答
0
投票

我认为环境变量不应该使用您在 file1.js 中完成的方法来设置,您应该只在 javascript 文件中读取它们,但是您可以使用 .bat 文件来设置它们:

ECHO on
SET [email protected]
SET dev_url=example.com
node file2.js

如果您需要使用 file1.js 来执行此操作,另一种可能的解决方案是将其导入到 file2.js 中

# file1.js
process.env.dev_url="example.com"

# file2.js
require('./file1.js')
console.log(process.env.user); 
console.log(process.env.dev_url); 

# runner.bat
ECHO on
SET [email protected]
node file2.js

© www.soinside.com 2019 - 2024. All rights reserved.