node中config的使用;

nodeconfig的使用;

概述:在项目中由于特殊需求,需要设置的一些配置变量在全局使用,这个时候就可以使用config包,来进行管理。

  1. 下载:传送门

  2. 使用:

    默认会加载当前项目根目录下的config文件夹下的配置,也可以自己设置加载路径process.env.NODE_CONFIG_DIR="./page"

    1. 会默认加在 default.js文件;
    2. 若是设置了环境变量developmentproductionenvName,则会加载对应的文件[nevNane].js,若是不设置环境变量env.NODE_ENV同时存在development的话则会默认加载。development.js
    例:
    const express = require('express');
    const app = express();
    
    /**
     * NODE_ENV的值如果为空则默认加载:development.js文件
     * 若设置对应的值,则会加载 [envName].js,通常会配合环境变量使用。
     */
    process.env.NODE_ENV = 'development'
    
    // HOSTNAME的值会加载对应的 [HOSTNAME].js文件,通常会配合域名使用。
    process.env.HOSTNAME = 'local.kps.netease.com'
    
    // 如果你的配置文件不在config文件夹内,那么你可以使用 NODE_CONFIG_DIR 值来设置你的配置文件夹名。
    process.env.NODE_CONFIG_DIR="./paghe"
    
    let config = require('config');
    
    console.log(process.env.NODE_ENV);
    app.get('/', (req, res) => res.send(config));
    app.listen(30000, () => console.log(`listen 3000`));
    

    注:local.js文件会始终加载,但只是最后加载。

    # 优先级:
    default.EXT
    default-{instance}.EXT
    {deployment}.EXT
    {deployment}-{instance}.EXT
    {short_hostname}.EXT
    {short_hostname}-{instance}.EXT
    {short_hostname}-{deployment}.EXT
    {short_hostname}-{deployment}-{instance}.EXT
    {full_hostname}.EXT
    {full_hostname}-{instance}.EXT
    {full_hostname}-{deployment}.EXT
    {full_hostname}-{deployment}-{instance}.EXT
    local.EXT
    local-{instance}.EXT
    local-{deployment}.EXT
    local-{deployment}-{instance}.EXT
    
    1、EXT can be .yml, .yaml, .xml, .coffee, .cson, .properties, .json, .json5, .hjson, .ts or .js depending on the format you prefer (see below)
    2、{instance} is an optional instance name string for Multi-Instance Deployments
    3、{short_hostname} is your server name up to the first dot, from the $HOST or $HOSTNAME environment variable or os.hostname() (in that order). For example if your hostname is www.example.com then it would load www.EXT.
    4、{full_hostname} is your whole server name, you may use this when {short_hostname} collides with other machines.
    5、{deployment} is the deployment name, from the $NODE_ENV (or if specified, $NODE_CONFIG_ENV) environment variable
    
posted @ 2021-01-07 13:00  古怪精灵  阅读(1636)  评论(0编辑  收藏  举报