1. 程式人生 > >Create an online IDE with Angular 6 + NodeJS ~ Part #2

Create an online IDE with Angular 6 + NodeJS ~ Part #2

Configure Environment Variables

Node apps, like most, work with multiple environments, that can be accessed through proccess.env.NODE_ENV value.The common environments are “development”, “testing” and “production” (the aliases are “dev”, “test”, “prod”).To clarify, NODE_ENV value (the current environment) configured by an “entity” from outside the app’s borders (E.g. the developer manually, or some NPM script).

Using the above, we can easily define different behavior in different environments, a little example (only to simplify the concept of different behavior — not a real-life example) :

const curEnv = proccess.env.NODE_ENV; let dbUri; if (curEnv == 'prod') {                 dbUri = 'prod.example-db.com'; // database for production
} else if (curEnv == 'test') { dbUri = '
test.example-db.com'; // database for testing } else { dbUri = 'dev.example-db.com'; // database for development}db.connect(dbUri); // different db on different environments

What a mass for something as trivial as assigning a value 🙄Try to avoid the approach of assigning a value to environment-depend variables (like dbUri

from this example) by if-else each of your environments.

The strategy commonly used to solve this issue is to store all the environment-depend values in one json file, and in one occasion, assign those values to the global object process.env , and with that, all this messy conditional value assignment we used in the example is gone 👍.

Now, all the environment-depend values, or values that considered sensitive from a security aspect (E.g. external API credentials, secret keys) will be stored on config.json file;

example for config.json file

here you’ll assign all the properties from one of the environments keys (that corresponds to the current environment) on config.json to process.env object.

Side-Note — you’re using require(‘./config.json’) and not the typical import statement. import statement must be called on the top of a .ts file, before all other definitions, and in this case you must import config.json inside the if block. Way is that ? config.json containing sensitive data, and will not be stored on git or the server (you’ll deploy to) for this app production, so importing config.json file on production will cause the app to crash, luckily 😏 the condition on the if statement [lines 14–20] will never be satisfied on production and the code inside it won’t be executed 👌.

import config.ts file on server.ts ;

import * as express from "express";import * as bodyParser from "body-parser";import './config/config.ts'; // include the '.ts' extensionimport { appRoutes } from './routes/app.routes';
class ExpressApp {    ....   ...