Javascript 读取 .config 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38404816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a .config file
提问by Alan Schambers
Currently I have a file called router.js set up as follows:
目前我有一个名为 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';
I would like to to be set up like this:
我想这样设置:
var Server = require('mongodb').Server;
var MongoDB = require('mongodb').Db;
var dbPort = readConfig(dbPort);
var dbHost = readConfig(dbHost);
var dbName = readConfig(dbName);
How would I go about accomplishing this. I would like to have a file such as test.config, and be able to read dbPort, dbHost, and dbName from that .config file in router.js.
我将如何实现这一点。我想要一个文件,例如 test.config,并且能够从 router.js 中的 .config 文件中读取 dbPort、dbHost 和 dbName。
回答by Timo
You could store your config as a JSON file and read it directly:
您可以将配置存储为 JSON 文件并直接读取:
config.json
配置文件
{
"dbPort": 31979,
"dbHost": "40.117.155.19",
"dbName": "node-login"
}
router.js
路由器.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;
回答by Lucas Watson
Here's one way to do it
这是一种方法
//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;