node.js - 使所需的 json 在其他模块中可用
问题描述
我正在编写一个在 json 文件中具有配置参数的应用程序。像这样的东西:
// config.json
{
"httpServer": {
"port": 3000
},
"module1": {
"setting1": "value1",
"setting2": "value2"
},
"module2": {
"setting1": "value1",
"setting2": "value2"
}
}
// index.js
const config = require("./config")
const func1 = require("./module1")
const func2 = require("./module2")
// code here
// module1.js
const config = require("./config")
// use config and define functions
module.exports = {
function: function
}
// module2.js
const config = require("./config")
// use config and define functions
module.exports = {
function: function
}
问题是我在每个模块中都需要这个文件,这使得我的代码无法维护,因为如果文件名发生更改,我需要更新每个 require 语句。我很确定这不是这样做的“正确”方式。我可以在程序启动时要求配置文件一次,然后在其他模块中引用它吗?或者我应该将配置文件作为命令行参数传递,然后在需要文件时使用 process.argv 数组?处理此类情况的最佳方法是什么?
解决方案
使用 dotenv 包npm install dotenv --save
,
创建一个配置文件
//config.env
NODE_ENV=development
IP=127.0.0.1
PORT=3000
加载配置文件
//index.js
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' })
随时随地使用它
//module1
console.log('IP: ',process.env.IP)
推荐阅读
- css - css 绝对没有涵盖所有内容
- spring-boot - 只能为 HMAC 签名指定 Base64 编码的密钥字节
- postgresql - Postgres 9.6 - 包含 jsons 数组的复杂查询 jsonb 字段
- c++ - 容器在使用前被销毁/修改时的 C++ 警告(通过引用元素或迭代器使用)
- react-native - 如何在本机反应中将字符串转换为base64?
- python - 使用 numpy 在 3D 网格上广播点积
- javascript - XMLHttpRequest() 无限循环
- ruby - 在 Ruby 中将字符串转换为数字
- ruby-on-rails - Ruby on Rails - 创建记录后设置属性
- wordpress - 如何在 wp 页面内容的 href 属性中添加 php 代码?