gpt4 book ai didi

javascript - 在 Node.js 中仅连接一次配置变量

转载 作者:行者123 更新时间:2023-12-03 08:33:02 25 4
gpt4 key购买 nike

我有一些文件:

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 :

工具包.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;

但我又出错了。

最佳答案

您需要从 toolkit.js 导出。因此,您的工具包将如下所示

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;

关于javascript - 在 Node.js 中仅连接一次配置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33275506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com