【JavaScript 学习--10】--configJS

本文介绍了一个用于配置管理的Node.js模块config的使用方法。通过示例展示了如何在不同环境中加载配置文件,并通过config模块API访问这些配置。演示了如何在开发和生产环境中设置不同的配置值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

configJS

快速开始

$ npm install config
$ mkdir config
$ vi config/default.json
{
  // Customer module configs
  "Customer": {
    "dbConfig": {
      "host": "localhost",
      "port": 5984,
      "dbName": "customers"
    },
    "credit": {
      "initialLimit": 100,
      // Set low for development
      "initialDays": 1
    }
  }
}
$ vi config/production.json
{
  "Customer": {
    "dbConfig": {
      "host": "prod-db-server"
    },
    "credit": {
      "initialDays": 30
    }
  }
}
my-app.js
const config = require('config'); 
//config.get() will throw an exception for undefined keys to help catch typos and ??missing values. 
//Use config.has() to test if a configuration value is defined.                                         
var dbConfig = config.get('Customer.dbConfig');  //和下面方法获得一样的结果                             
var dbConfig2 = config.Customer.dbConfig                                    
console.log(dbConfig); 
console.log('-----------');                                              console.log(dbConfig2);  

如果这个时候运行 node my-app.js的话,结果如下

{ host: 'localhost', port: 5984, dbName: 'customers' }
-----------
{ host: 'localhost', port: 5984, dbName: 'customers' }

假如我们改变一点点

$ export NODE_ENV=production
$ node my-app.js

结果将会

{ host: 'prod-db-server', port: 5984, dbName: 'customers' }
-----------
{ host: 'prod-db-server', port: 5984, dbName: 'customers' }

Running in this configuration, the port and dbName elements of dbConfig will come from the default.json file, and the host element will come from the production.json override file.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木瓜~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值