javascriptnode.jsdiscord.jsnode.js-fs

ReferenceError: Cannot access 'fs' before initialization


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.


Solution

  • In my case, I was not passing "fs" as string inside require.

    Just changing to const fs = require("fs"); worked.

    Screenshot of error:

    enter image description here