简体   繁体   English

nodeJS开发生产环境配置文件加载

[英]nodeJS development and production environment config file loading

Based on this answer here https://stackoverflow.com/a/22524056/777700 I have set exactly the same configuration options, but it doesn't work.基于这里的答案https://stackoverflow.com/a/22524056/777700我设置了完全相同的配置选项,但它不起作用。

My (partial) app.js file:我的(部分)app.js 文件:

console.log('environment: '+process.env.NODE_ENV);

const config = require('./config/db.json')[process.env.NODE_ENV || "development"];

console.log(config);

My ./config/db.json file:我的 ./config/db.json 文件:

{
    "development":{
        "host":"localhost",
        "port":"3306",
        "username":"root",
        "password":"",
        "database":"dbname"
    },
    "production":{
        "host":"production-host",
        "port":"3306",
        "username":"user",
        "password":"pwd",
        "database":"dbname"
    }
}

Console.log outputs: Console.log 输出:

environment: development
undefined

and app crashes.和应用程序崩溃。 Any idea why?知道为什么吗? File is there, if I remove the [...] part of require(), it does print out the db.json file, with it, it prints out undefined.文件在那里,如果我删除 require() 的 [...] 部分,它会打印出 db.json 文件,它会打印出未定义的文件。

EDIT I tried to add console.log(typeof config) just after require() to see what I'm getting and I have noticed that if I require('./config/db.json')[process.env.NODE_ENV] I get undefined , but if I require('./config/db.json')["development"] I get back proper object.编辑我试图在 require() 之后添加console.log(typeof config)以查看我得到了什么,我注意到如果我require('./config/db.json')[process.env.NODE_ENV]我得到undefined ,但如果我require('./config/db.json')["development"]我得到正确的对象。

Versions:版本:

nodeJS 6.11.4
express 4.16.2

After more debugging and searching online, I have finally found the solution.经过更多的调试和网上搜索,我终于找到了解决方案。 The problem is that I'm on Windows machine and I was using npm run dev command while my "dev" command looked like SET NODE_ENV=development && nodemon server.js .问题是我在 Windows 机器上,我使用的是npm run dev命令,而我的“dev”命令看起来像SET NODE_ENV=development && nodemon server.js

Experienced eye will notice a space before && , which added a space behind the variable development , so the variable I was comparing against was "development " and not "development" as I was thinking.有经验的眼睛会注意到&& 之前有一个空格,它在变量development后面添加了一个空格,所以我比较的变量是"development "而不是我想的"development"

So, the original answer from other question does work and it does load proper config!因此,来自其他问题的原始答案确实有效,并且确实加载了正确的配置!

You should export configuration as a variable:您应该将配置导出为变量:

const config = {
    "development":{
        "host":"localhost",
        "port":"3306",
        "username":"root",
        "password":"",
        "database":"dbname"
    },
    "production":{
        "host":"production-host",
        "port":"3306",
        "username":"user",
        "password":"pwd",
        "database":"dbname"
    }
};
module.exports = config;

This way it will be found :)这样就可以找到了:)

If you want to do it via JSON:如果您想通过 JSON 执行此操作:

const fs = require('fs')
let localConfig

try {
    localConfig = JSON.parse((fs.readFileSync('./config/db.json', 'utf-8'))
} catch (e) {
    console.log('Could not parse local config.')
    localConfig = false
}

module.exports = localConfig

You could then add logic for production, if there's no local configuration localConfig will return false and you can look for environment variables injected at that point.然后您可以为生产添加逻辑,如果没有本地配置localConfig将返回 false 并且您可以查找此时注入的环境变量。

Update:更新:

I see that you're giving the production config yourself, in that case you can just access the key you need based on the environment.我看到您自己提供了生产配置,在这种情况下,您可以根据环境访问所需的密钥。 Just import localConfig and use the keys you need.只需导入localConfig并使用您需要的密钥。

Its better to use dotenv package for this最好为此使用 dotenv 包

npm i dotenv npm 我 dotenv

Step 1: In package.json add this第 1 步:在 package.json 中添加这个

"scripts": {
    "start": "nodemon app.js",
    "dev": "NODE_ENV=dev nodemon app.js"
    "prod": "NODE_ENV=prod nodemon app.js"
  },

Step 2: Add .env.prod and .env.dev files第 2 步:添加 .env.prod 和 .env.dev 文件

.env.dev .env.dev

PORT=7200
# Set your database/API connection information here
DB_URI=localhost
DB_USERNAME=root
DB_PASSWORD=password
DB_DEFAULT=dbName

Step 3: Add this in config.js第 3 步:在 config.js 中添加它

const dotenv = require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });

const result = dotenv;
if (result.error) {
  throw result.error;
}
const { parsed: envs } = result;
// console.log(envs);
module.exports = envs;

Step 4: Use like this when needed第 4 步:在需要时像这样使用

const {
  DB_URI, DB_USERNAME, DB_PASSWORD, DB_DEFAULT,
} = require('../config');

Now if u want for development, run现在如果你想要开发,运行

npm run dev

For prod, use对于产品,请使用

npm run prod

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

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