From 75f5b281678b52863df02428566c5d0766db18ae Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Sat, 30 Apr 2022 13:00:04 +0100 Subject: [PATCH] Last Sync: 2022-04-30 13:00:04 --- Programming_Languages/NodeJS/Environments.md | 35 ++++++++++++++++++++ Programming_Languages/NodeJS/Middleware.md | 8 ++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/Programming_Languages/NodeJS/Environments.md b/Programming_Languages/NodeJS/Environments.md index 019dd79..cbe8f56 100644 --- a/Programming_Languages/NodeJS/Environments.md +++ b/Programming_Languages/NodeJS/Environments.md @@ -4,3 +4,38 @@ tags: - backend - node-js --- +# Environments + +With a full-scale Node application you will typically run three environments: +* Development +* Testing +* Production + +### Accessing current Node environment + We can control which processes run in a particular environment via the Node envrionment variables: `process.env` (see for instance [ports](./Ports.md)). + +To determine the current environment we can use the variable `process.env.NODE_ENV`. This works globally regardless of the kind of Node app we are building. In Express, there is a built in method for retrieving the current envrionment: `app.get('env')`. + +If you haven't manually set up your environments Node will return `undefined` but express defaults to `development`. + +```js + +console.log(process.env.NODE_ENV); // undefined +console.log(app.get("env")); // development + +``` + +Here is an example of setting middleware to run only in the specified environment: + +```js +if (app.get("env") === 'development') { + app.use(morgan("common")); + console.log('Morgan enabled') +} +``` +### Setting the current environment +We could test that the previous code block works by switching the environment to production. We would do this by setting the environment variable in the terminal: + +``` +export NODE_ENV=production +``` \ No newline at end of file diff --git a/Programming_Languages/NodeJS/Middleware.md b/Programming_Languages/NodeJS/Middleware.md index 0333854..5697cdf 100644 --- a/Programming_Languages/NodeJS/Middleware.md +++ b/Programming_Languages/NodeJS/Middleware.md @@ -117,7 +117,6 @@ console.log(app.get("env")); // development ``` -### We can set Morgan to run only in development with: ```js @@ -126,3 +125,10 @@ if (app.get("env") === 'development') { console.log('Morgan enabled') } ``` + +### Setting the current environment +We could test that the previous code block works by switching the environment to production. We would do this by setting the environment variable in the terminal: + +``` +export NODE_ENV=production +``` \ No newline at end of file