It apparently fails to find the module - javascript

The code is this and when I try to turn my bot on I get a error that it can't find the file to execute the command.
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFolders = fs.readdirSync('./commands')
for(const folder [enter image description here][1]of commandFolders){
const command_files = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'))
for(const file of command_files){
const command = require(`./commands/${folder}/${file}`);
if(command.name){
client.commands.set(command.name, command);
}else {
continue
}
}
}
}
This is the error I get when I turn my bot on.
node:internal/modules/cjs/loader:944
throw err;
^
Error: Cannot find module './commands/Fun/8ball.js'
Require stack:
- C:\Users\Desktop\Discordproject\handlers\command_handler.js
- C:\Users\Desktop\Discordproject\index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:941:15)
at Function.Module._load (node:internal/modules/cjs/loader:774:27)
at Module.require (node:internal/modules/cjs/loader:1013:19)
at require (node:internal/modules/cjs/helpers:93:18)
at module.exports (C:\Users\Desktop\Discordproject\handlers\command_handler.js:8:25)
at C:\Users\famil\Desktop\Discordproject\index.js:11:37
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\Desktop\Discordproject\index.js:10:38)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\Desktop\\Discordproject\\handlers\\command_handler.js',
'C:\\Users\\Desktop\\Discordproject\\index.js'
]
}
Directory Structure:

Your command_handler.js file is inside /handlers/. ./ is used to access the current directory.
Doing ./commands/ doesn't work because the commands folder is not inside of /handlers/
You must first exit the current folder (using ../), then access.
Change all of the './commands' to '../commands'

Related

Error message keeps appearing even tho there is a file dedicated to that code - Discord.js

So i have been trying to fix this issue for a while now and even rewrote some bits but so far it still keeps giving the same thing... Below is the code and the terminal output
This is done using node.js and discord.js
Main Bot Code
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.color = "";
client.commandarray = [];
const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync(`./src/functions/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of functionFiles)
require(`./functions/${folder}/${file}`)(client);
}
client.handleEvents();
client.handleCommands();
client.login(token);
The Terminal Output
C:\Users\Maheel\Desktop\NewTestingBOt\src\bot.js:17
require(`./functions/${folder}/${file}`)(client);
^
TypeError: require(...) is not a function
at Object.<anonymous> (C:\Users\Maheel\Desktop\NewTestingBOt\src\bot.js:17:45)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Thanks in advance to those who help with this error message
Please make sure that what your exporting from that file is a function, and not an object.
function:
module.exports = (param) => {
console.log("hello world")
}
object:
module.exports = {
helloWorld: () => {
console.log("hello world")
}
}

Error: Cannot find module 'renderer/utils/localStore'

I am trying to call userDir function to get userdata folder path in the main/main.ts. I am using the electron-react-boilerplate
const electron = require('electron');
const path = require('path');
const fs = require('fs');
export function userDir() {
return (electron.app || electron.remote.app).getPath('userData');
}
I am caling the userDir function in the main.ts file
import { userDir } from 'renderer/utils/localStore';
userDir()
Error:
Electron encountered an error
Error: Cannot find module 'renderer/utils/localStore'
Require stack:
- /home/prash/Projects/Electron/pomodoro/src/main/main.ts
- /home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/electron#18.3.2/node_modules/electron/dist/resources/default_app.asar/main.js
-
at Module._resolveFilename (node:internal/modules/cjs/loader:940:15)
at Function.n._resolveFilename (node:electron/js2c/browser_init:245:1105)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/#cspotcode+source-map-support#0.8.1/node_modules/#cspotcode/source-map-support/source-map-support.js:811:30)
at Function.Module._load (/home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/runtime-required#1.1.0/node_modules/runtime-required/runtime-required.js:28:44)
at Module.require (node:internal/modules/cjs/loader:1012:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/home/prash/Projects/Electron/pomodoro/src/main/main.ts:15:1)
at Module._compile (node:internal/modules/cjs/loader:1116:14)
at Module.m._compile (/home/prash/Projects/Electron/pomodoro/node_modules/.pnpm/ts-node#10.8.0_wxuian5givsywcqjoc4lpn66fa/node_modules/ts-node/src/index.ts:1597:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1169:10)
```

./index.js is recognized as a module

./commands/hello.js:
const discord = require("discord.js")
const client = require("./index.js").client
const { prefix } = require("./config/config.json")
const { hello } = "./config/config.js"
//modules
module.exports = () => {
//onClient
client.on("messageCreate", (message) => {
if (!message.content.startsWith(`${prefix}hello`)) return
//creating the embed
const embed = new discord.MessageEmbed()
.setTitle("test")
.setAuthor("Sanke")
.addField("Test", "this is a test")
.setDescription("This is a test commmand")
//message send
message.channel.send({
content:"",
embeds: [embed],
files: []
})
})
}
index.js:
const { Client,Intents } = require("discord.js")
const { token } = require("./config/config.json")
const fs = require('fs')
//Client init
const client = new Client({ intents: [Intents.FLAGS.GUILDS]})
exports.client = client
client.once('ready', () =>{
console.log("First time seeing ya face on discord :)")
client.user.setActivity("First time here :D")
})
//comand Handler
const command = require("./commands/hello")
command()
client.login(token)
Problem:
-in ./commands/hello.js is recognized as a module,not a target file. I don't know what to do...I tried to make the command handler with the const command = require("./commands(commands directory)/hello(the command file)")
-Error:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module './index.js'
Require stack:
- /Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/commands/hello.js
- /Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/commands/hello.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/commands/hello.js',
'/Users/sanki/Desktop/Sanke_<:>/proiecte/theBot/index.js'
]
}
It looks from the code you shared that you're trying to require ./index.js inside commands/hello.js. Shouldn't that be ../index.js?
The next problem you're likely to encounter is a circular dependency - each file requires the other.
Can you remove the require of index.js in hello.js and pass the client to the hello command directly? E.g.
index.js
const { Client, Intents } = require("discord.js")
const { token } = require("./config/config.json")
const fs = require('fs')
//Client init
const client = new Client({ intents: [Intents.FLAGS.GUILDS]})
exports.client = client
client.once('ready', () =>{
console.log("First time seeing ya face on discord :)")
client.user.setActivity("First time here :D")
})
//comand Handler
const command = require("./commands/hello")
// CHANGE >> PASS CLIENT TO COMMAND
command(client)
client.login(token)

Unexpected Token in discord.js node_modules/#discordjs/src/rest/APIRequest.js:34

Full Error:
c:\Users\beed\.vscode\HTML + JS\Javascript\Mystic-Sneaky_Helper_2\node_modules\discord.js\src\rest\APIRequest.js:34
agent ??= new https.Agent({ ...this.client.options.http.agent, keepAlive: true });
^^^
SyntaxError: Unexpected token '??='
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (c:\Users\beed\.vscode\HTML + JS\Javascript\Mystic-Sneaky_Helper_2\node_modules\discord.js\src\rest\RESTManager.js:5:20)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
[Done] exited with code=1 in 0.117 seconds
I used VSCode, I followed the DisordJS Guide, I used Code Runner to run the JavaScript.
==== DIVIDER ====
Directory:
commands
ping.js
node_modules
#discord.js
rest
APIRequest.js
Some More Modules...
NOTE: I ONLY SHOWED THE MODULE THE ERROR IS IN.
config.json
deploy_commands.js
index.js
package-lock.json
package.json
It took me some time to write the directory above, so please answer...
Index.js:
// Require the necessary discord.js classes
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json')
const fs = require('fs')
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
client.commands = new Collection()
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
==== DIVIDER ====
Thanks in advance,
Beedful
You need to upgrade to Node.JS v15.0.0+
Since the error is Unexpected token '??=', you should try to add engines in your package.json
"engines": {
"node": "16.x"
}
let me know if it works.

|Discord Bot Error: Cannot find module './commands/ban.js'

My code
require('dotenv').config();
const fs = require('fs');
const Discord = require('discord.js')
const { error } = require('console');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const PREFIX = "zm.";
const commandFiles = fs.readdirSync(`./commands/`).filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.login(process.env.BOT_TOKEN);
client.on('ready', () =>{
console.log('ZeKuS Modification bot is now online!');
client.user.setActivity('ZeKuS Modification | ZM', {type: 'PLAYING'}).catch(console.error)});
client.on('message', message =>{
if (message.author.bot) return;
if (!message.content.startsWith(PREFIX)) return;
const args = message.content.slice(PREFIX.length).trim().split(/\s+/);
const cmd = args.shift();
const commandFiles = fs.readdirSync(`./commands/`).filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
if (!client.commands.has(command)) return;
try{
client.commands.get(cmd).execute(message, args);
} catch (error){
console.error(error);
message.reply('there was an error trying to execute that command!');
}
})
//verify
//ban
client.on('guildMemberAdd', member => {
console.log(member.user.tag);
});
Error:
Error: Cannot find module './commands/ban.js'
Require stack:
- c:\Users\uporabnik\Documents\GitHub\zm-bot\src\bot.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
at Function.Module._load (internal/modules/cjs/loader.js:862:27)
at Module.require (internal/modules/cjs/loader.js:1042:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (c:\Users\uporabnik\Documents\GitHub\zm-bot\src\bot.js:13:21)
at Module._compile (internal/modules/cjs/loader.js:1156:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'c:\\Users\\uporabnik\\Documents\\GitHub\\zm-bot\\src\\bot.js' ]
}
My folderss:
enter image description here
Error: Cannot find module './commands/ban.js'
Require stack:
c:\Users\uporabnik\Documents\GitHub\zm-bot\src\bot.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
Basicly it trows the error and Im not sure how to fix it, please help since Im just stuck at the mmoment
Your folder structure looks like this:
ZM-Bot/
|
Commands/
| |
| ban.js
|
src/
|
app.js
If you want to require ban.js from app.js, you need to navigate out of src/ first.
So the path is ../commands/ban.js.
const commandFiles = fs.readdirSync(`../commands/`).filter(file => file.endsWith('.js'));

Categories