Let’s scroll through the Nodejs environment variable (process.env)

SERVER_PATH, BASEURL, VUE_APP_TITLE, SERVER_PATH, BASEURL, VUE_APP_TITLE, etc

First, what is process.env?

The process object is a global variable that provides information about and controls the current Node.js process. The process.env attribute returns an object containing the user environment, as shown below (official example) :

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'nodejscn',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/nodejscn',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/nodejscn',
  LOGNAME: 'nodejscn',
  _: '/usr/local/bin/node'
}
Copy the code

Yes, it is an object, not my object, not your object

It is the process.env property in the Nodejs application that returns the object containing the user environment, so it cannot be used in client-side code. It is simply a packaged static resource in the browser.

At this time, someone said (if) : no, they can use it when writing the Vue project. For example, VUE_APP_TITLE can be accessed like this:

console.log(process.env.VUE_APP_TITLE)
Copy the code

VUE_APP_TITLE, VUE_APP, VUE_APP_TITLE, VUE_APP_TITLE, VUE_APP

When writing a Vue project, in the client-side code, only variables starting with VUE_APP_ are statically embedded in the client-side package by webpack.defineplugin, so you can access them in the application code; Of course, there are also two special variables that can be accessed in the application: NODE_ENV and BASE_URL; Official explanation: The portal

Also, in the React application, except for some built-in variables (NODE_ENV and PUBLIC_URL), variable names must start with REACT_APP_.

How to modify?

Use process.env well, and of course know how to modify it, like with a girlfriend, well, I don’t have a girlfriend.

Anyway, how do I fix it?

A: Direct assignment.

process.env.girlfriend = 100
console.log(process.env.girlfriend)
Copy the code

Why is it a string? The smart ones have already figured it out.

We do not recommend this kind of behavior, do not cheat and play with women’s feelings of men, single-minded.

Well, we really don’t recommend this behavior, because assigning an attribute on process.env implicitly converts the value to a string:

process.env.girlfriend = true;
console.log(process.env.girlfriend);
// => 'true'

process.env.girlfriend = 1;
console.log(process.env.girlfriend);
// => '1'

process.env.girlfriend = null;
console.log(process.env.girlfriend);
// => 'null'

process.env.girlfriend = undefined;
console.log(process.env.girlfriend);
// => 'undefined'

process.env.girlfriend = {a: 'aa'};
console.log(process.env.girlfriend);
// => '[object Object]'
Copy the code

Also, future versions of Node.js may throw errors if the value is not a string, number, or Boolean.

Add, delete, change and check, how to delete? Just delete:

process.env.girlfriend = 1;
delete process.env.girlfriend
console.log(process.env.girlfriend);
// => undefined
Copy the code

Note that on Windows, environment variables are case-insensitive:

process.env.GIRLFRIEND = 1;
console.log(process.env.girlfriend);
// => 'q'
Copy the code

How to easily switch the environment?

In a company, a project will typically have a development version, a test version, an online version, and perhaps a pre-live version, each with different parameters, such as the address of the requested API, or the address of the image font resource, etc.

To facilitate management, we usually make it in the form of configuration files, and load different files according to different environments. After all, I have to find a girlfriend. I can’t be too low.

Modify the package.json file

For example, the environment variable girlfriend that we’re setting now

{
  ...,
  "scripts": {
    "normal": "export girlfriend='woman' && node friend.js",
    "sages": "export girlfriend='monster' && node friend.js" // 在windows上export要换成set
  },
  ...
Copy the code

NPM run Normal is the normal mode

NPM Run Sages is the Sage mode

Now we can configure package.json to set the environment variable and get the corresponding value in the code, so we can easily change the environment.

Don’t worry, you can use cross-env dependencies to configure environment variables across platforms. Install dependencies:

npm install --save-dev cross-env
Copy the code

Configure the environment

"scripts": {
  "normal": "cross-env girlfriend='woman' node friend.js"
}
Copy the code

This is not a lot better

No, the sage mode has many different scenarios, such as duration, location, etc., and a lot of spelling at the end is also very low.

There are several ways to solve this problem, such as writing an env module

// env.js module.exports = {'normal': {// exports in normal mode}, // other mode}Copy the code

Then different commands load different objects to modify the environment variable:

const envConfig = require('env.js')[process.env.NODE_ENV];
if (Object.prototype.toString.call(envConfig) === '[object Object]') {
  for (const k in envConfig) {
    process.env[k] = envConfig[k]
  }
}

Copy the code

Of course, there are many other ways.

In this case, I recommend using the.env file in conjunction with the Dotenv dependency package.

All right, I’m gonna get serious.

About dotenv

Dotenv is a zero-dependency package that loads environment variables from the.env file to process.env; Env files are parsed as JSON objects and the key-value pairs are assigned as environment variables by process.env, which can then be used by process.env[key].

The basic usage process is as follows

The installation

# with npm
npm install dotenv

# or with Yarn
yarn add dotenv
Copy the code

use

Require ('dotenv').config() // default. Env fileCopy the code

It loads the contents of the.env file in the project root directory into process.env.

We can also use its Parse method to retrieve a JSON object

const fs = require('fs')
const dotenv = require('dotenv')
const config = dotenv.parse(fs.readFileSync('.env')) // will return an object
console.log(typeof config, config) // object { girlfriend : 'woman' }
Copy the code

For more on this, see portal

Share my solution

First, different environments correspond to different.env files, such as.env.beta,.env.prod;

The env file

NODE_ENV = 'development'
HOST = 'lacalhost'
PORT = 3000
MONGODB_HOST = '127.0.0.1'
MONGODB_USERNAME = 'root'
MONGODB_PASSWORD = '123'
Copy the code

. The env. Prod file

NODE_ENV = 'production'
HOST = '10.100.xx.xx'
PORT = 3000
MONGODB_HOST = '43.247.xx.xx'
MONGODB_USERNAME = 'root'
MONGODB_PASSWORD = 'xxxxxx'
Copy the code

Then in the scripts command, use the –mode parameter to distinguish between different environments and correspond to the relevant file names;

Package. The json file

{
  ...,
  "scripts": {
    "dev": "cross-env nodemon server/index.js --watch",
    "prod": "cross-env node server/index.js --mode prod"
  },
  ...
}
Copy the code

Argv, and load the different. Env files according to the different mode, so that we can easily change environment;

Server/index. Js file

const dotenv = require('dotenv')
const argv = process.argv
const mode = argv[2] === '--mode' ? argv[3] : ''
const envFile = mode ? `.env.${mode}` : '.env'
dotenv.config({ path: envFile })
Copy the code

Argv (process.argv, process.argv, process.argv, process.argv) Such as:

// package.json
"scripts": {
  "dev": "cross-env nodemon server/index.js --watch --mode dev"
}

// server/index.js
console.log(process.argv)
// => ['xxx', 'xx', 'dev']
Copy the code

If you want to get the parameters the way I do, you must declare:

// package.json
"scripts": {
  "dev": "cross-env nodemon server/index.js --mode dev --watch"
}
Copy the code

I don’t quite understand the content of process.argv. Please forgive me if there is any mistake.

The last

New Year, new beginning, I hope you can find your object in the New Year

In this paper, to the end.

Ruizer. Making. IO/blog/note/n…