簡體   English   中英

覆蓋nodejs中的配置文件 - 最佳實踐?

[英]overwrite config file in nodejs - best practice?

想知道什么是我的案例的最佳實踐。 我有一個變量,我需要在應用程序加載時設置它的值,並在我的代碼中多次訪問這個值。 獲得這個價值的最好方法是什么? 現在我只是覆蓋配置文件屬性。 全局變量更好嗎? 還有另一種方法嗎?

配置恕我直言的優先級標准是:

  1. 命令行參數
  2. 環境變量
  3. 本地配置文件
  4. 全局配置文件

如果沒有找到 cli 參數,則查看環境變量,然后是本地配置文件,然后是全局

我這樣做。

  1. 將變量放入.env文件中:

     #.env APP_PORT=4000
  2. 在我的應用程序源代碼中,我創建了一個名為constants.js的文件:

     // constants.js import { load as loadEnvVars } from 'dotenv'; // run `npm i dotenv` to install // load the.env file content to process.env loadEnvVars(); // export the variables I need export const APP_PORT = process.env.APP_PORT || 3000;
  3. 我在需要時導入該文件,如下所示:

     // server.js import Express from 'express'; // import the constant import { APP_PORT } from './constants'; const app = Express(); app.listen(APP_PORT, () => console.log('server deployed');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM