background

Recently open pit NodeJS development, this paper mainly realizes loading different server configuration in JSON according to different environment variables

Write config.json to provide the server configuration

Config. json stores server configurations in different environments. This example includes development, staging, and production environments:

{

"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"

}

}

Copy the code

Write config.js to load the server configuration

NODE_ENV is the environment variable in config.js, and the default is 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]);

}

Copy the code

Use the configuration within the environment variable

Require (‘./config/config’) within the NodeJS project; Process.env.params, for example, can be used to distinguish port numbers in different environments:

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

const http = require('http');



const port = normalizePort(process.env.PORT || '3000');

app.set('port', port);

const server = http.createServer(app);

Copy the code

Write startup commands for different environments in package.json

Through the export NODE_ENV = development | | SET \ “NODE_ENV = development \” to Linux and Windows series system environment variables were SET up and start NodeJS The project can actually load different environment variable configurations.

"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"

},

Copy the code