【发布时间】:2019-08-01 13:44:05
【问题描述】:
我不知道如何构建我的代码,或者更确切地说,我不知道使用以下结构构建应用时会发生什么。我需要使用redis,所以可以在每个模块中调用它还是这是一种不好的做法?
我有 10 个函数,我想在单独的模块中拥有这些函数,以保持我的代码可读性。我正在使用 express js。
所以我有一个 index.js,它看起来像这样:
const express = require("express");
const app = express();
const port = 3001;
// the separate modules I want to make
let myFirst = require("./first_function");
let mySecond = require("./second_function");
//etc...
app.use("/my_route1",myFirst);
app.use("/my_route2",mySecond);
app.listen(port, () => console.log(`Listnening on port ${port}`));
first_function.js 文件如下所示:
const express = require("express");
const router = express.Router();
const redis = require("redis");
const { promisify } = require("util");
const REDISHOST = process.env.REDISHOST;
const REDISPORT = process.env.REDISPORT;
const redisClient = redis.createClient(REDISPORT, REDISHOST);
const getAsync = promisify(redisClient.get).bind(redisClient);
redisClient.on("error", function(err) {
return;
// but since this is an http function should I be calling res.end()?
});
router.all("/", (req,res) =>{
// code for my function
});
module.exports = router;
我将在相当多的模块中使用 redis,那么将 index.js 文件制作成数千行代码会更好吗?我不太明白当需要一个模块时会发生什么,如果我使用 10 个都需要 redis 的模块,然后从 index.js 需要这些模块,我最终会得到 10 个 redis 客户端吗?
【问题讨论】:
-
您可以将所有redis代码写入1个文件并导出redisClient。然后导入 redisClient 以在需要的地方使用。
-
节点是否有任何类型的标头系统,我可以告诉它,当代码被调用时,不在此模块范围内的变量将在范围内?
标签: node.js node-modules