How it works...

Let's start by determining the environment. The standard is to set an environment variable called NODE_ENV with the name of the environment, before running the Node server itself. How to do that would depend on your actual machine, but in Linux, it would be something akin to the following, while in Windows the SET command would be required:

> export NODE_ENV=production 
> echo $NODE_ENV
Production

In your code, you could set a isDev variable to true if you are running in development (and false otherwise) with just two lines. If no environment was specified, the first line makes it default to "development", which is most likely the safest choice:

// Source file: show_env.js

const
dev = process.env.NODE_ENV || "development";
const isDev = dev === "development";

Then, for example, you could have set different logging levels easily: see the following code snippet, regarding how the level attribute gets its value, depending on the environment:

const logger = winston.createLogger({
transports: [
new winston.transports.Console({
level: isDev ? "info" : "warn",
format: winston.format.combine(
winston.format.colorize({ all: true }),
.
.
.

Changing the log file would also be simple, along the same lines as the preceding code:

let loggingFile;
if (isDev) {
loggingFile = "serv_http_errors.log";
} else {
loggingFile = "/var/log/http_server.txt"
;
}

const morganStream = fs.createWriteStream(loggingFile, {
flags: "a"
});

This style works, but it still has a couple of problems:

  • Any change in the environment requires changing the (hardcoded) server
  • The paths, tokens, passwords, and more, all reside in the source code, in a very viewable state

So, we can do even better by directly taking the values for our internal variables directly from the environment:

const DB_HOST = process.env.DB_HOST;
const DB_USER = process.env.DB_USER;
const DB_PASS = process.env.DB_PASS;
const DB_SCHEMA = process.env.DB_SCHEMA;
const SECRET_JWT_KEY = process.env.SECRET_JWT_KEY;

Alternatively, for logging, we could use the following:

const logger = winston.createLogger({
transports: [
new winston.transports.Console({
level: process.env.WINSTON_LEVEL,
format: winston.format.combine(
winston.format.colorize({ all: true }),
.
.
.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.255.86