在 node.js 中的模块之间传递 mysql 连接

Passing the mysql connection between modules in node.js

有几个类似的问题,但我仍然找不到答案。 我正在 discord.js 中创建一个不和谐的机器人,其中每个命令都是一个单独的模块,我不知道如何解决传输连接到每个文件的问题。

这是我的文件树:

bot
├─index.js
├─my_modules/
│ └─db.js
└─commands/
  ├─exampleCommand.js
  ├─...
  └─subCommandsForExampleCommand/
    ├─subCommand1.js
    └─...

db.js:

const mysql = require(`mysql`);

var conn = mysql.createConnection({
    //user, pass, etc..
});

//some db functions

module.exports = conn;

来自 node.js 文档:

Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from node_modules folders), it is not a guarantee that require('foo') will always return the exact same object, if it would resolve to different files.

index.js 中使用 require(`./my_modules/database.js`) 和在 subCommand1.js 中使用 require(`../../my_modules/database.js`) 可能 return 不同的实例。那么如何最好地传递文件之间的连接呢?

将连接作为参数从 index 传递到 exampleCommand 并从此处传递到 subCommand1,或者在索引中设置一个全局变量并在其他文件中使用它?

你做的很好。 并且文档意味着如果您在不同的地方有多个名为 db.js 的文件,您可能会碰巧加载不同的文件,具体取决于您从哪里加载。 IE。如果你只是 require('moduleName') 有一个解析机制,它从当前目录开始,然后移动到其他地方,比如节点模块等。只要你有一个 db.js 并且没有类似命名的节点模块,你应该没问题。