Module.exports vs Plain json用于配置文件 [英] Module.exports vs plain json for config files
问题描述
我看到了在Node.js中创建配置文件的多种方法.一种使用js文件中的module.exports,一种仅使用普通的json对象.
I see multiple ways to create config files in Node.js. One uses module.exports in js file, one just use plain json object.
// config1.js
module.exports = {
config_1: "value 1",
config_2: "value 2"
}
// config2.json
{
"config_1": "value 1",
"config_2": "value 2"
}
在配置文件中使用module.exports有什么好处吗?有什么区别?
Is there any advantages of using module.exports in config file? What are the differences?
推荐答案
javascript CommonJS模块
- 评论
- 条件
- 循环等填充默认值
- 基于NODE_ENV或类似代码更改配置的代码
- 代码以查找用于SSL密钥,API凭证等的外部文件
- 更容易拥有后备和默认值
- comments
- conditionals
- loops and such to populate defaults
- code to change config based on NODE_ENV or similar
- code to look for external files for SSL keys, API credentials, etc
- easier to have fallbacks and defaults
- 易于使用外部工具进行解析和更新
- 与几乎所有的编程语言兼容
- 无需执行即可加载的纯数据
- 易于打印的漂亮
- JSON可以作为基础,上面描述的有关CommonJS模块的所有代码项都可以存在于config.js模块中,该模块读取config.json作为起点
javascript CommonJS Module
因此,为了方便起见,我总是从commonjs模块开始,但是其中的任何逻辑都保持简单.如果您的config.js有错误并需要测试,则可能太复杂了.吻.如果我知道一个事实,我的配置中还会有其他问题,我将使用JSON文件.
So I always start with a commonjs module for the convenience, but keep any logic in there simple. If your config.js has bugs and needs tests, it's probably too complicated. KISS. If I know for a fact other things are going to want poke around in my config, I'll use a JSON file.
这篇关于Module.exports vs Plain json用于配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!