'Nodejs unable to detect folder after directory structure change
Our team is working on a discord bot in javascript. Recently I was working on the API (for a dashboard) on a separate branch and then I noticed that commands stopped registering because it could not find the commands directory. This was after a directory change,All of the bot's content was in the root directory before the change but is now in the bot directory, I checked if the directory was correct and it was! It didn't work with relative paths but absolute paths work! Here is the code for the command handler (only loading part)
const Categories = ['fun', 'moderation', 'server'];
const commandsDir = path.join('./', 'commands');
logger.info('loading commands...', 'Command_Handler');
Categories.forEach((Category) => {
fs.readdir(path.join(commandsDir, Category), (error, files) => {
if (error) {
logger.error(
new Error(`Error In Reading Command Files:\n${error}`),
'Command_Handler'
);
} else {
files.forEach((file) => {
if (!file.endsWith('.js'))
logger.error(
new Error(`A File Does Not Ends With .js`, 'Command_Handler')
);
let command = require(path.join(commandsDir, Category, file));
if (!command.name || !command.aliases)
logger.error(
new Error(
`No Command Name & Command Aliases In A File`,
'Command_Handler'
)
);
if (command.name) client.commands.set(command.name, command);
if (command.aliases)
command.aliases.forEach(
(alias) => client.aliases.set(alias, command.name),
logger.success(`registered ${command.name}`, 'Command_Handler')
);
if (command.aliases.length === 0) command.aliases = null;
});
}
});
});
Here is the directory structure:
The code is in index.js
Update
I fixed it by replacing const commandsDir = path.join('./', 'commands'); with const commandsDir = path.join(__dirname, 'commands');
Solution 1:[1]
Use commandsDir: path.join(__dirname, 'commands') it should work for ts node
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mushroomator |

