[英]Manage config in nodejs to get variables from file and env variables
我有一個配置文件,其中存儲了密碼並使用了數據
'use strict';
export default {
dbProd: {
connectionString: 'postgres://...',
},
dbDev: {
connectionString: 'postgres://...',
},
...
}
我也有一個PostgreSQL數據庫連接文件
'use strict';
import { Pool } from 'pg';
import config from './../config';
export default new Pool({
connectionString: config.dbDev.connectionString,
ssl: true
});
在我的package.json
文件中,有三個腳本。 第一個啟動項目,第二個開發,第三個用於生產
"scripts": {
"start": "nodemon --exec babel-node src/index.js",
"devbuild": "babel src --out-dir dev-backend",
"build": "babel src --out-dir backend"
},
當我收集用於生產的項目以通過dbProd
連接到數據庫,並且開發已轉移到dbDev
就需要dbDev
。 如何執行呢?
您應該考慮使用node-package config
NPM Config ,因為它使這些事情變得更加容易。
您只需要在/config
文件夾中創建一個default.json
文件,其中將包含所有開發配置以及在開發或生產中都不會更改的配置。 您必須創建的第二個文件是production.json
文件,其中包含覆蓋默認key:values的所有生產配置。
在package.json
您只需要一個用於生產環境的開始腳本和一個用於開發的腳本。 可能看起來像這樣:
"start": "SET NODE_ENV=production& node ./bin/www",
"dev": "node ./bin/www",
通過設置NODE_ENV=production
,配置模塊將加載默認配置並查看生產文件,以找出在生產模式下必須覆蓋哪些值。
default config file
一個簡單示例:
{
"Services": {
"api": {
"username": "user",
"password": "password",
"base_url": "https://development.com/test"
}
},
"Network": {
"proxy": {
"host": "http://myproxy/",
"port": 80
}
}
}
如果代理始終相同並且僅API發生更改,那么production file
將如下所示:
{
"Services": {
"api": {
"username": "prodUser",
"password": "prodPassword",
"base_url": "https://production.com/test"
}
}
}
現在,可以像下面這樣在您的代碼中使用它:
const config = require('config');
const serviceConfig = config.get('Services');
const networkConfig = config.get('Network');
networkConfig.get('proxy.host')+":"+networkConfig.get('proxy.port')
您需要使用配置包或任何其他流行的包,這些包允許您為每種環境定義不同的配置。
使用config,您必須制作/ config文件夾,您可以在其中將每個配置放入每個環境,如下所示:
/config/development.json
/config/production.json
用法:
var config = require('config');
//...
var dbConfig = config.get('Customer.dbConfig');
db.connect(dbConfig, ...);
if (config.has('optionalFeature.detail')) {
var detail = config.get('optionalFeature.detail');
//...
}
該軟件包使用NODE_ENV環境變量值來確定要使用的配置,因此您必須在啟動應用程序之前設置此變量。
$ export NODE_ENV=production
$ node my-app.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.