Nodejs配置文件

专栏收录该内容

Hi I'm Shendi




一个程序中,配置文件是不可或缺的

在 nodejs 中,可以使用 node-config 来使用配置文件。



安装依赖

使用以下命令安装依赖

npm install config


使用

node-config支持很多格式的配置文件,但我比较喜欢使用json,所以这里只列出json的示例

项目下新建一个config文件夹,文件夹内存放配置文件,首先需要新建一个默认配置文件 default.json

文档地址:https://github.com/node-config/node-config/wiki/Configuration-Files

default.EXT文件被设计为包含其他文件可能覆盖的所有配置参数。重写是在逐个参数的基础上完成的,因此后续文件只包含该重写唯一的参数。

其中EXT为后缀,可以是 .yml, .yaml, .xml, .coffee, .cson, .properties, .json, .json5, .hjson, .ts ...


我的目的仅仅是将少量参数作为配置文件,所以配置文件不会太大,这里就直接使用 default.json 存储所有信息

内容如下

{
    "name" : "Shendi",
    "version" : 1.0,
    "hello" : {
        "world" : "hello,world"
    },
    "site" : ["sdpro.top", "tool.sdpro.top"]
}


引入依赖

const config = require('config');

通过 get 来获取配置

// Shendi
config.get("name");
// 1.0(数字类型,自动转为1)
config.get("version");
// hello,world
config.get("hello.world");
// 数组 ["sdpro.top", "tool.sdpro.top"]
config.get("site");


需要注意的是,通过 get 获取配置文件,如果不存在的话会抛出错误,例如 config.get("test")

可以通过 has 先判断参数是否存在,存在再去 get




END

本文链接:https://sdpro.top/blog/html/article/1090.html

♥ 赞助 ♥

尽管去做,或许最终的结果不尽人意,但你不付出,他不付出,那怎会进步呢?