简体   繁体   English

如何从NodeJS中的文件设置process.env?

[英]How to set process.env from the file in NodeJS?

I'm new to the Node.JS. 我是Node.JS的新手。 I found few articles says we can use .env file to setup the process.env variable, eg, 我发现很少有文章说我们可以使用.env文件来设置process.env变量,例如,

PORT = 8081

but when I run the program in my node, it is still 8080 PORT (by default). 但是当我在我的节点中运行程序时,它仍然是8080 PORT(默认情况下)。 The question is how can I setup the env variable in Node without any other 3rd party module's help? 问题是如何在没有任何其他第三方模块帮助的情况下在Node中设置env变量? (I found there are few 3rd party package to management the env config, but... it is kind confused, different package might have different rule and more complex use cases; I want to start from clear way to study purely nodejs) (我发现很少有第三方软件包来管理env配置,但是......它很混乱,不同的软件包可能有不同的规则和更复杂的用例;我想从明确的方式开始纯粹研究nodejs)

Update 更新

I have read Node Environment Setting post on StackOverFlow, but they are refer using 3rd party package, none of them tells the detail steps. 我已经在StackOverFlow上阅读了Node Environment Setting帖子,但它们是使用第三方软件包引用的,它们都没有说明详细步骤。 (Either windows system environment, or Linux environment variables... but how can I place the setting into my project folder?!) (无论是Windows系统环境,还是Linux环境变量......但是如何将设置放入我的项目文件夹?!)

Dotenv file have become the most popular mode to separate configuratione from app, using system environment variables (see 12factor config ). Dotenv文件已经成为使用系统环境变量将配置与app分离的最流行模式(参见12factor config )。

On node there exists a lot of libraries for loading config from .env file. 在节点上有很多用于从.env文件加载配置的库。 The most popular is motdotla/dotenv . 最受欢迎的是motdotla / dotenv You can read a lot of examples on readme file about the usage of this library 您可以在自述文件中阅读有关此库用法的大量示例

Make a config.js file with the following content: 制作包含以下内容的config.js文件:

module.exports = {
    bar: 'someValue',
    foo: 'otherValue'
    ...
}

Then you can do this in some file: 然后你可以在一些文件中执行此操作:

const config = require('./config');
let foo = config.foo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM