ReferenceError:初始化前无法访问“fs”

Che*_*e33 5 fs node.js discord.js

我尝试在discordjs bot (v13) 上使用fs,但出现一个奇怪的错误。

在我可以 console.log 我的 fs 对象和错误之间实际上有 3 行:

// 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;
    }
});
Run Code Online (Sandbox Code Playgroud)

和错误:

/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
Run Code Online (Sandbox Code Playgroud)

我错过了什么?提前致谢。

jfr*_*d00 14

该特定错误意味着在您的函数作用域中的其他地方(未在您的问题的代码中显示),您可能有const fs = ...or let fs = ...,因此尝试fs在此函数作用域中重新定义,该函数作用域隐藏了更高的作用域fs

该错误意味着您尝试在执行此范围内的变量或定义fs之前使用该变量。与 with (其中定义在内部提升)不同,您不能在使用or声明变量之前使用变量。const fs = ...let fs = ...varletconst

根据我们可以看到的代码位,我猜您是在语句case中的其他处理程序之一switch或包含此语句的函数中的其他位置执行此操作switch。当您不使用大括号为每个case处理程序定义新范围时,这些处理程序都在同一范围内,并且其中的所有const定义let可能会相互干扰。

fs因此,请在该函数的其他位置寻找重新定义。而且,如果这对您来说不是很明显,请发布该函数发生错误的所有代码。


这是一个重现完全相同错误的独立示例。这是您应该寻找的东西:

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
Run Code Online (Sandbox Code Playgroud)

当您运行此命令时,会出现以下错误:

ReferenceError: Cannot access 'fs' before initialization
Run Code Online (Sandbox Code Playgroud)

fs或者,类似地,如果您在包含该语句的同一函数中的其他位置定义switch,但在该switch语句之后。这也会导致同样的问题。

  • @Chenille33 - 这是一个很好的例子,说明您应该如何在模块顶部(在模块作用域和模块初始化时)而不是在函数内声明导入。而且,当您使用 ESM 模块(该语言的未来)时,您将被迫在模块的顶部进行这些类型的静态导入。不管怎样,很高兴你明白了。 (3认同)

Kus*_*eth 0

就我而言,我没有"fs"作为内部字符串传递require

只是改变const fs = require("fs");工作。

错误截图:

在此输入图像描述