There were several similar questions, but I still can't find the answer. I'm creating a discord bot in discord.js where each command is a separate module and I don't know how to solve transfer a connection to each file.
This is my file tree:
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;
From the node.js documentation:
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.
Using require(`./my_modules/database.js`)
in index.js
and require(`../../my_modules/database.js`)
in subCommand1.js
may return different instances. So how best to transfer the connection between files?
Pass the connection as an argument from the index
to exampleCommand
and from here to subCommand1
, or set a global variable in the index and using it in other files?
It's fine the way you did it.
And the docs mean that if you have multiple files named db.js
in different places, you may happen to load different files depending on where you're loading from. I.e. if you just require('moduleName')
there's a resolving mechanism which starts with the current directory and then moves on to other places like node modules etc. As long as you have one db.js
and also no node modules named similarly, you should be ok.