【问题标题】:Should I require in each module?我应该在每个模块中要求吗?
【发布时间】: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


【解决方案1】:
const redis = require('redis');

class Connection {

    constructor() {
        this.redisClient = redis.createClient({host : "<hostname>", port : "<port>"});
        let methods = {};
        methods.redisF = false;
        if(this.redisconf.cache) {
            this.redisClient.on('ready',function() {
            methods.redisF = true;
            console.log(" Redis cache is up and running ... ");
            });
        }
        this.redisClient.on('error',function() {
            methods.redisF = false;
        });
    }
    static makeRedisConnection() {
        try {
            return this.redisClient;
        } catch(error) {
            throw "error"
        }
    }
}

module.exports = Connection;

当你想从redis查询时,通过以下方式从任何其他模块的任何异步函数中获取连接,它将帮助你编写更少和更多结构化的代码。

const redis_conn = Connection.makeRedisConnection();

【讨论】:

  • 有没有办法导出对一个处理数据库连接的对象的引用?我不想为每个端点函数调用打开一个新连接。我可能正在以错误的方式思考事情。也许我会为每个函数运行一个单独的服务器实例。
  • 这里我们做同样的事情,连接只在项目启动和类加载时建立一次。然后我们使用保存连接的“this.redisClient”实例变量。所以我们不是每次都连接。希望我回答了你的问题。
  • 我想我在关注,我在 node.js 网站上读到他们缓存了对 require 的调用。因此,即使您需要一个模块 x 次,它也不会触发该模块内的代码......当然这有例外。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2011-11-06
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多