目前我有一个名为router.js的文件设置如下:
var Server = require('mongodb').Server;
var MongoDB = require('mongodb').Db;
var dbPort = 31979;
var dbHost = '40.117.155.19';
var dbName = 'node-login';
我想这样设置:
var Server = require('mongodb').Server;
var MongoDB = require('mongodb').Db;
var dbPort = readConfig(dbPort);
var dbHost = readConfig(dbHost);
var dbName = readConfig(dbName);
我将如何完成此任务。我想有一个文件,如test.config,并能够从router.js中的.config文件中读取dbPort,dbHost和dbName。
答案 0 :(得分:25)
您可以将配置存储为JSON文件并直接读取:
<强> config.json 强>
{
"dbPort": 31979,
"dbHost": "40.117.155.19",
"dbName": "node-login"
}
<强> router.js 强>
var Server = require('mongodb').Server;
var MongoDB = require('mongodb').Db;
var CONFIG = require('./config.json');
var dbPort = CONFIG.dbPort;
var dbHost = CONFIG.dbHost;
var dbName = CONFIG.dbName;
答案 1 :(得分:3)
这是一种方法
//File config.js
module.exports = {
dbPort : 8080,
dbHost : etc,
dbName : nom,
}
//File server.js
var Server = require('mongodb').Server;
var MongoDB = require('mongodb').Db;
var config = require('configFile');
var dbPort = config.dbPort;
var dbHost = config.dbHost;
var dbName = config.dbName;