Home > OS >  ReferenceError: Cannot access 'fs' before initialization
ReferenceError: Cannot access 'fs' before initialization

Time:05-02

I try to use fs on a discordjs bot (v13) but I have a strange error.

I have literally 3 lines between the moment when I can console.log my fs object and the error :

// Get FS
const fs = require('fs');

// Recieves commands
client.on('interactionCreate', async interaction => {
    console.log(fs); // OK
    switch(interaction.commandName) {
        // Get list of all maps for this server
        case 'maps':
            const pngfiles = fs.readdirSync('./maps/').filter(f => f.endsWith(".png")); // NOT OK !!!!!!!
            response = "**List all maps available in this server:**\n\n\n" pngfiles.join("\n") "\n";
            break;
    }
});

And the error :

/home/chenille33/DPW/app.js:156
                const pngfiles = fs.readdirSync('./maps/').filter(f => f.endsWith(".png"));
                                 ^

ReferenceError: Cannot access 'fs' before initialization
    at Client.<anonymous> (/home/chenille33/DPW/app.js:156:34)
    at Client.emit (node:events:527:28)
    at InteractionCreateAction.handle (/home/chenille33/DPW/node_modules/discord.js/src/client/actions/InteractionCreate.js:74:12)
    at module.exports [as INTERACTION_CREATE] (/home/chenille33/DPW/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (/home/chenille33/DPW/node_modules/discord.js/src/client/websocket/WebSocketManager.js:351:31)
    at WebSocketShard.onPacket (/home/chenille33/DPW/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/chenille33/DPW/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/chenille33/DPW/node_modules/ws/lib/event-target.js:199:18)
    at WebSocket.emit (node:events:527:28)
    at Receiver.receiverOnMessage (/home/chenille33/DPW/node_modules/ws/lib/websocket.js:1137:20)

Node.js v18.0.0

What I've missed ? Thanks in advance.

CodePudding user response:

That specific error implies that somewhere else in your function scope (not shown in the code in your question), you likely have const fs = ... or let fs = ... and are thus attempting to redefine fs in this function scope which is hiding the higher scoped fs.

The error means that you're trying to use the variable fs BEFORE its const fs = ... or let fs = ... definition in this scope have been executed. Unlike with var (where definitions are internally hoisted), you can't use a variable before its declaration with let or const.

Based on the bit of code we can see, I would guess you're doing this in one of the other case handlers in your switch statement or somewhere else in the function containing this switch statement. When you don't use braces to define a new scope for each case handler, then those are ALL within the same scope and all const or let definitions there can interfere with each other.

So, look for a redefinition of fs somewhere else in this function. And, if that isn't obvious to you, then post all the code for this function where the error occurs.


Here's a stand-alone example that reproduces that exact same error. This is the kind of thing you should be looking for:

let greeting = "hi";
const fs = require('fs');

switch (greeting) {
    case "hi":
        fs.readFileSync("temp.js");
        console.log("got hi");
        break;
    case "goodbye":
        const fs = require('fs');       // this redefinition causes the error
                                        // when the "hi" case executes
        console.log("got goodbye");
        break;
    default:
        console.log("didn't match");
        break;
}

// or a redefinition of fs here (in the same function) would also cause the error

When you run this, it gives this error:

ReferenceError: Cannot access 'fs' before initialization

Or, similarly, if you were defining fs somewhere else in the same function containing the switch statement, but after the switch statement. That would also cause the same problem.

  • Related