The Error message "ReferenceError: Cannot access 'readdirSync' before initialization at Object.<anonymous>" is caused by trying to access the 'readdirSync' function before it has been initialized

Today I encountered an error while trying to modify my command handler based on a YouTube video tutorial. The video was uploaded in April and the method worked for the creator, but unfortunately not for me. Despite my efforts, I couldn't find a solution to this issue. Although I am still learning, I am determined to begin my journey like many others in this incredible community that has been so supportive and helpful. Thank you for all the support! I remain optimistic that I will overcome this obstacle.



const Timeout = new Discord.Collection();
const bot = new Discord.Client(); 
const prefix = '$';
bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');
const ms = require('ms');
const {readdirSync , read} = require('fs');

for(const folder of commandsFolders){
    const commandFiles  = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
    for(const file of commandFiles){
        const command = require(`./commands/${folder}/${files}`);
        bot.commands.set(command.name, command);
    }
}

bot.on("error" , console.error);

bot.once('ready' , () => {
    console.log('I have risen from the dead!');
});

bot.on("message" , async (message) =>{
     if(message.author.bot) return;
     if(message.channel.type === 'dm') return;
     
     if(message.content.startsWith(prefix)){
         const args = message.content.slice(prefix.length).trim().split(/ +/);
         
         const commandName = args.shift().toLowerCase();

         const command = bot.command.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
         if(!command) return;

         if (command) {
             if(command.cooldown){
                 if(Timeout.has(`${command.name}${message.author.id}`)) return  message.channel.send(`Please wait! \`${ms(Timeout.get (`${command.name}${message.author.id}`) - Date.now(), {long: true})}\`Before using this command again!`);
                 command.run(bot, message, args)
                 Timeout.set(`${command.name}${message.author.id}` , Date.now() + command.cooldown)
                 setTimeout(() =>{
                     Timeout.delete(`${coomand.name}${message.author.id}`)
                 }, command.cooldown)
             } else command.run(bot, message, args); 
         }
     }
})

Answer №1

One common mistake is trying to use readdirSync before importing the fs library into your code. Simply rearrange the require statement so that it comes before readdirSync, and everything should function correctly:

const bot = new Discord.Client(); 

const prefix = '$';

const {readdirSync , read} = require('fs');

bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');

const ms = require('ms');

for(const folder of commandsFolders){
    const commandFiles  = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
    for(const file of commandFiles){
        const command = require(`./commands/${folder}/${files}`);
        bot.commands.set(command.name, command);
    }
}

bot.on("error" , console.error);

bot.once('ready' , () => {
    console.log('I'm alive again!');
});

bot.on("message" , async (message) =>{
    if(message.author.bot) return;
    if(message.channel.type === 'dm') return;

    if(message.content.startsWith(prefix)){
        const args = message.content.slice(prefix.length).trim().split(/ +/);

        const commandName = args.shift().toLowerCase();

        const command = bot.command.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
         if(!command) return;

         if (command) {
             if(command.cooldown){
                 if(Timeout.has(`${command.name}${message.author.id}`)) return  message.channel.send(`Please wait! \`${ms(Timeout.get (`${command.name}${message.author.id}`) - Date.now(), {long: true})}\`Before using the command again!`);
                 command.run(bot, message, args)
                 Timeout.set(`${command.name}${message.author.id}` , Date.now() + command.cooldown)
                 setTimeout(() =>{
                     Timeout.delete(`${coomand.name}${message.author.id}`)
                 }, command.cooldown)
             } else command.run(bot, message, args); 
         }
     }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to show a nested div element within a v-for loop in Vue.js?

One interesting feature of my coding project is that I have an array nested within another array, and I iterate through them using two v-for loops. The challenge arises when I try to display a specific div in the second loop only upon clicking a button. ...

Vaadin 23 failing to process URLs, resulting in the display of an error page instead

Issue Overview: After upgrading our Java 17 monolith application with multiple modules from Vaadin 21.0.1 to 23.3.5, our application routes are no longer resolving and are resulting in 404 Whitelabel error pages. Having worked with Vaadin before (originati ...

Is it possible to use JavaScript or jQuery to call a WCF Service and retrieve a collection of System.IO.Stream objects?

I am developing a WCF service that will be utilized by plain JavaScript on the client side, as well as some jQuery JavaScript. 1) How can I set up the plain client JavaScript to call the WCF Service in a manner that retrieves a collection of System.IO.Str ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

Can you explain the concept of "excluded" in relation to project subdirectories on Webstorm?

When using Webstorm, you have the option to mark project subdirectories as "excluded". However, the full implications of this designation remain unclear in the Webstorm documentation. Does marking a directory as excluded impact debugging or deployment proc ...

The _doc property within Mongoose

I need assistance with this JavaScript code I have: app.post('/auth', async (req, res) => { try { const user = UserModel.findOne({email: req.body.email}).exec() if (!user) return res.status(404).json({ message: ...

Checking for the uniqueness of a username with joi: A step-by-step guide

A while back, I came across an interesting article that discussed using Joi for asynchronous validation to check the uniqueness of a username by querying the database. Sadly, I can't seem to locate it now and I'm curious about how we can implemen ...

Exploring Angular2: The Router Event NavigationCancel occurring prior to the resolution of the Route Guard

My application has routes protected by an AuthGuard that implements CanActivate. This guard first checks if the user is logged in and then verifies if certain configuration variables are set before allowing access to the route. If the user is authenticated ...

Is there a way for me to verify whether an object is an instance of a stream in node.js?

I'm currently attempting to verify if a specific object (this) is an instance of a stream. I'm struggling with determining whether it remains the original this deep within the function after it has been triggered. I've experimented with usi ...

Encountering a 404 Error when using Next.js Route Handlers

I am currently faced with an issue in my Next.js project involving the new Route Handlers feature. The problem arises when I attempt to handle a POST request from a form within a client component, resulting in a persistent 404 error. Below is the layout o ...

Adding default values to a Vuejs data property

My goal is to populate the predefined data property that I have set. reportGroupData: [ { program_name: "", iteration_name: "", report_template_name: "", toggle: true, report_details: [], }, ] This po ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

Data is not appearing when using Node.js with mongoose and the populate() method

I am facing an issue while trying to display data from a database. Even though I have integrated 3 different schemas into one, the combined data is not being displayed as expected. I have attached all three schemas for reference. While async-await along w ...

Nest JS encountering an error due to an undefined property

Recently, my application was running smoothly until I attempted to fetch the documentation using Swagger. It seems like there might be a dependency issue causing it to stop working, but I can't pinpoint the root of the problem. An error message keeps ...

Ways to widen the header to fit the entire page?

I'm having trouble stretching my header to fill the entire page. I've tried using margin-left and right, but it's not working as expected. My Header CSS: background: green; height: 70px; width: 100%; display: flex; just ...

What is the process for including an SVG file in my JavaScript .textContent?

I've been struggling to add an exclamation SVG to this section, but for some reason I can't make it work. I've searched on Google for a solution, but haven't found one yet. The SVG file is already downloaded and stored in my project fo ...

Obtaining input value from a JavaScript function

Using the highcharts 4 JavaScript library allows for customizing chart buttons. Check out a chart with custom buttons To customize buttons in highcharts, you can push button objects into an array and include this array in the Highcharts configuration. H ...

What is the best way to store a JSON file as a variable in Node.js?

After reviewing my post, I realized that I need to clarify the intent behind it. The question at hand is not related to the code or the equality operator, but rather about how to represent a JSON file in a variable. Let me rephrase my query: How can I crea ...

Encountering an 'undefined is not a function' error despite the defined reference

I've been grappling with understanding why this specific line in my code is throwing an error that says 'undefined is not a function'. Here is the associated Plunker. // This line shows the function to be invoked console.log((compileStrateg ...

Use JavaScript to generate an HTML element that has an attribute mirroring its text content

Trying to figure out how to create an HTML element similar to this: <option value="Replaced">by this</option> For example: <option value="ThisIsTest">ThisIsTest</option> UPDATE Using jQuery, I need to achieve something like thi ...