Last Sync: 2022-04-30 13:00:04
This commit is contained in:
parent
33ae359f7d
commit
75f5b28167
2 changed files with 42 additions and 1 deletions
|
@ -4,3 +4,38 @@ tags:
|
||||||
- backend
|
- backend
|
||||||
- node-js
|
- 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
|
||||||
|
```
|
|
@ -117,7 +117,6 @@ console.log(app.get("env")); // development
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
###
|
|
||||||
We can set Morgan to run only in development with:
|
We can set Morgan to run only in development with:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
@ -126,3 +125,10 @@ if (app.get("env") === 'development') {
|
||||||
console.log('Morgan enabled')
|
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
|
||||||
|
```
|
Loading…
Add table
Reference in a new issue