NodeJS 实现环境配置

2,398 阅读1分钟
原文链接: blog.dongsj.cn

背景

近期开坑 NodeJS 开发,该文主要实现了根据不同的环境变量加载 JSON 内的不同服务器配置

编写 config.json 提供服务器配置

config.json 内存储了不同环境下的各服务器配置,该例包含 development、staging、production 三个环境:

{
"development": {
"PORT": 3000,
"MONGODB_URI": "mongodb://localhost:27017/baoheJM",
"DB":"baoheJM"
},
"staging": {
"PORT": 9201,
"MONGODB_URI": "mongodb://localhost:27017/baoheJM-STA",
"DB":"baoheJM-STA"
},
"production": {
"PORT": 9201,
"MONGODB_URI": "mongodb://localhost:27017/baoheJM-PRO",
"DB":"baoheJM-PRO"
}
}

编写 config.js 加载服务器配置

config.js 内根据环境变量 NODE_ENV 加载了对应的各个环境变量配置,并默认使用 development:

let env = process.env.NODE_ENV || 'development';
if (env === 'development' || env === 'staging' || env === 'production') {
console.log('server config loaded');
console.log(env);
const config = require('./config.json');
Object.assign(process.env, config[env]);
}

使用环境变量内的配置

使用时在 NodeJS 项目内 require('./config/config'); 即可加载,并通过 process.env.params 拿到各个配置,例如 express 的后台项目可通过该方式来区分不同环境下的端口号:

const app = require('../app');
const http = require('http');

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
const server = http.createServer(app);

在 package.json 内编写不同环境的启动命令

通过 export NODE_ENV=development || SET \"NODE_ENV=development\" 来分别设置 Linux 和 Windows 系列系统的环境变量后再启动 NodeJS 项目即可真正加载不同的环境变量配置。

"scripts": {
"start-dev": "export NODE_ENV=development || SET \"NODE_ENV=development\" && pm2 start ./bin/www --name baoheJM-dev",
"start-sta": "export NODE_ENV=staging || SET \"NODE_ENV=staging\" && pm2 start ./bin/www --name baoheJM-sta",
"start-pro": "export NODE_ENV=production || SET \"NODE_ENV=production\" && pm2 start ./bin/www --name baoheJM-pro"
},