我有一些文件:
tags.js:
var express = require('express'),
router = express.Router(),
monk = require('monk'),
db = monk('localhost:27017/data');
...
module.exports = router;
records.js:
var express = require('express'),
router = express.Router(),
monk = require('monk'),
db = monk('localhost:27017/data');
...
module.exports = router;
users.js:
var express = require('express'),
router = express.Router(),
monk = require('monk'),
db = monk('localhost:27017/data');
...
module.exports = router;
我必须始终复制标题:
var express = require('express'),
router = express.Router(),
monk = require('monk'),
db = monk('localhost:27017/data');
连接配置变量一次的最佳解决方案是什么?
我尝试了这个变种In Node.js, how do I "include" functions from my other files?,但这不起作用,因为我应该在tools.js中使用require(例如:require('express'))并且我得到了错误。
我还尝试此变体node.js - accessing required variables from other files:
toolkit.js:
var express = require('express'),
router = express.Router(),
monk = require('monk'),
db = monk('localhost:27017/data');
tags.js:
var tools = require('../toolkit'),
router = tools.router;
router.get('/', function(req, res) {
...
});
module.exports = router;
但我又犯了错误。
答案 0 :(得分:1)
您需要从toolkit.js
导出。因此,您的toolkit
看起来像
var express = require('express');
exports.router = express.Router();
var monk = require('monk');
exports.db = monk('localhost:27017/data');
现在,你可以这样做:
var toolkit = require('path/to/toolkit');
var router = toolkit.router;
var db = toolkit.db;