commands

So in a tutorial I watched, a guy was putting his commands in index.js, if I move the commands to another file, will it still work? The command:
client.on('messageCreate', (message) => {
if (message.content === "ping") {
message.channel.send("pong")
}
client.on('messageCreate', (message) => {
if (message.content === "ping") {
message.channel.send("pong")
}
5 Replies
d.js toolkit
d.js toolkit2y ago
• What's your exact discord.js npm list discord.js and node node -v version? • Post the full error stack trace, not just the top part! • Show your code! • Explain what exactly your issue is. • Not a discord.js issue? Check out #useful-servers.
Oscar
Oscar2y ago
So CommonJS works like this: You have your main folder (index.js), this is the folder you run. Any code you put here is executed without hassle. Now, if I wanted to call a function in another file, say the function is called sendHelloWorld, simply putting sendHelloWorld(); in the index.js folder won't work. Instead, you must go to your sendHelloWorld.js file and write the following code: module.exports = { sendHelloWorld } What this does is it essientially exports your function saying "hey other files, you can use this function". Now, the way to import this function is to do this: const { sendHelloWorld } = require('./sendHelloWorld.js'); Final code for index.js file:
const { sendHelloWorld } = require('./sendHelloWorld.js');
sendHelloWorld();
const { sendHelloWorld } = require('./sendHelloWorld.js');
sendHelloWorld();
Final code for sendHelloWorld.js:
function sendHelloWorld() {
console.log("Hello, world!");
}

module.exports = { sendHelloWorld }
function sendHelloWorld() {
console.log("Hello, world!");
}

module.exports = { sendHelloWorld }
Tecrubeli Armut
Tecrubeli ArmutOP2y ago
Index.js:
const { sendPong } = require('./sendPong.js');
sendPong();
}
const { sendPong } = require('./sendPong.js');
sendPong();
}
module.exports = { sendPong } sendPong.js:
client.on('messageCreate', (message) => {
if (message.content === "ping") {
message.channel.send("pong")
}
client.on('messageCreate', (message) => {
if (message.content === "ping") {
message.channel.send("pong")
}
@oscartwo is this good then?
Oscar
Oscar2y ago
No the require bit is importing the code from another file the exports bit is exporting a thing to a file this thing must be an object, it could be an array, an object, a function, etc so if I wanted to export a function to a file, I'd first have to make the function in a file and then export it it then in my main file I'd import it if that makes sense anyway, this is more of a server for Discord JS help than a general JS help server
Tecrubeli Armut
Tecrubeli ArmutOP2y ago
Yeah Thank you for your help
Want results from more Discord servers?
Add your server