首页 > 解决方案 > 使所需的 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 数组?处理此类情况的最佳方法是什么?

标签: node.jsjsonconfigurationrequire

解决方案


使用 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)

推荐阅读