[Express.js] Global variables and configuration files

Global variables and configuration files

Usually we will write the configuration information of some projects into a file, and then read it into memory and use it. There are many schemes for using global variables in express, let's take a look at the commonly used schemes

Preparation

Copy the HelloWorld project in the first section

Prepare a Resp.js module:

module.exports = {
    
    
    Ok: (...args)=>{
    
    
        return {
    
    
            code: 200,
            msg: args[0]?args[0]:"Ok",
            data: args[1]?args[1]:null
        }
    }
}

global

Mount the amount we need to share globally in the global object. For example, if we want to mount a global config as the configuration of the entire express application, set it once at the top of the project's only entry file (such as: index.js, app.js, etc.) (priority to any module ) :

// index.js
global.config = {
    
    
    appname: "GlobalVar"
}
/** 更简洁的写法,隐变量,首次被执行到后,会自动挂载到全局
config = {
    appname: "GlobalVar"
}
*/
//创建app应用...

In this way, we can call config anywhere else, such as creating a new router.js and mounting it to the express application

// router.js
const routes = require('express').Router();
routes.get('/global', (req, res, next)=>{
    
    
    res.send(Resp.Ok("global中的全局变量", {
    
    "appname":config.appname}));
});

module.exports = routes;

// index.js
app.use(routes);

If we have a lot of configurations that need to be shared globally, it is somewhat unsightly to squeeze them above index.js, then we can write them in a file, and then import them at the top of index.js

// global.js
global.config = {
    
    
    appname: "GlobalVar"
}

// index.js
require('./global');

**Note:**Because the variables in the global can be xxxcalled directly by the variable name, there is no need global.xxx. If the variable name is set more common, such as the above config, or even simpler a, it is likely to conflict with the temporary variable defined in other modules, causing variable pollution. Therefore, the name must be special when mounting the variable on the global, for example: the previous replacement configis__config

global.__config = {
    
    
    appname: "GlobalVar"
}

advantage:

  • easy to call

shortcoming:

  • possible variable contamination
  • No code prompt, don't feel at ease

module

Customize a module, store some variables, and import them where needed
For example: we build a config.js by ourselves

// config.js
module.exports = {
    
    
    appname: "GlobalVar"
}

Introduce config.js in router.js

// router.js
const CONFIG = require('./config');

routes.get('/module', (req, res, next)=>{
    
    
    res.send(Resp.Ok("config模块当作全局变量", {
    
    "appname":CONFIG.appname}));
});

advantage:

  • Can have code hints
  • no variable pollution

shortcoming:

  • It is troublesome to import every time

app.set

Set the global variables in the application in the application settings table of express:

// index.js
app.set("appname", "GlobalVar");

Call the app in other places, such as the router mounted on the app:

// router.js
routes.get('/app', (req, res, next)=>{
    
    
    res.send(Resp.Ok("app中的'全局'变量", {
    
    "appname":req.app.get("appname")}));
});

In the sub-application mounted under the app, call the settings in the parent app. When a field is not set in the sub-application, it will inherit the field in the parent application

//subapp.js
const app = require('express')();
const Resp = require('./Resp');
//当子应用没有设置时,会继承父应用中设置的字段
// app.set('appname', "subapp");
app.all('/', (req, res, next) => {
    
    
    res.send(Resp.Ok("子应用获取父应用中的全局变量", {
    
    
        appname: req.app.get("appname")
    }));
})

module.exports = app;

//index.js
const subapp = require('./subapp');
app.use('/subapp',subapp);

advantage:

  • Can have code hints

process.env

Mount global variables in the environment variables of the process:

//index.js
process.env.appname = "GlobalVar";

Called elsewhere process.env.appname:

// subapp2.js
const app = require('express')();
const Resp = require('./Resp');

app.all('/', (req, res, next) => {
    
    
    // console.log(app.settings.env);
    res.send(Resp.Ok("在process.env上挂载全局变量", {
    
    
        appname: process.env.appname
    }));
})

module.exports = app;

//index.js
const subapp2 = require('./subapp2');
app.use('/process.env',subapp2);

shortcoming:

  • No code prompt, don't feel at ease

json

The above solutions all write the configuration information in the js file, which is a bit of a joke for a formal project. After all, the variables written in js can be easily changed. Most of the time, configuration information needs to be changed and is not allowed to be changed. We only need static information. In Js projects, json files are often used as static configuration files.

Create a new config.json file:

{
    
    
	"appname": "GlobalVar"
}

Add a new test to our router, no matter where you require, after being required for the first time, modifying the content of the json file will no longer have an impact

routes.get('/json', (req, res, next)=>{
    let configJson = require('./config.json');
    res.send(Resp.Ok("json静态配置文件", {"appname":configJson.appname}));
});

The json file does not support comments. If you want to comment, you can either save the country with a curve (add key-value pairs related to the commented key), or use the Json5 specification

npm install json5

Create a new config.json5 file:

{
    "appname": "GlobalVar"  //应用名
}

Then introduce register in the entry file of the project, and it will be mounted globally:

require('json5/lib/register');

Then require can parse json5the file:

routes.get('/json5', (req, res, next)=>{
    
    
    let configJson5 = require('./config.json5');
    res.send(Resp.Ok("json5静态配置文件", {
    
    "appname":configJson5.appname}));
});

yaml

Compared with .jsonfiles, .yaml(or .yml) files are more current configuration files. JSON files have strict format requirements, and yaml (yml) is more natural to write.
Create a new config.yaml file:

# 应用名
appname: GlobalVar  # 应用名

Reading yaml in nodeJs requires fs and js-yaml :

npm install fs
npm install js-yaml

Just mount fs to the global (the previous global.js), and generally do not take the local variable name like fs. If you need to operate files frequently, it will be much more convenient to mount to the global:

global.fs = require('fs');

Introduce and create a new test route in router.js js-yaml:

const yaml = require('js-yaml');

routes.get('/yaml', (req, res, next)=>{
    
    
    /*Object */
    let configYaml = yaml.load(fs.readFileSync('./config.yaml'));
    res.send(Resp.Ok("yaml动态配置文件", {
    
    "appname":configYaml.appname}));
});

Since the yaml file is read through fs, after changing the content in the yaml file, the result of accessing the route will also change


This article introduces a total of 6 solutions. There is no absolute statement on which one to use in the project, and it can be adapted to local conditions.

Next Section - Error Classification and Log Grading

Guess you like

Origin blog.csdn.net/m0_51810668/article/details/131818404