引用错误:初始化前无法访问'fs'



我尝试在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:**nnn"+pngfiles.join("n")+"n";
break;
}
});

和错误:

/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

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

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

这个错误意味着你试图在const fs = ...let fs = ...定义在这个范围内被执行之前使用变量fs。与var(其定义在内部提升)不同,您不能在letconst声明之前使用变量。

根据我们可以看到的代码位,我猜您正在switch语句中的其他case处理程序之一或包含此switch语句的函数中的其他地方这样做。当你不使用大括号为每个case处理程序定义一个新的作用域时,那么这些都在同一个作用域内,并且所有的constlet定义都可以相互干扰。

所以,在这个函数的其他地方寻找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

当你运行这个时,它会给出这个错误:

ReferenceError: Cannot access 'fs' before initialization
或者,类似地,如果您在包含switch语句的同一函数的其他地方定义fs,但是在switch语句之后。这也会导致同样的问题。

在我的情况下,这是因为我有一个名为const process = null的变量导致node.js进程被覆盖。

所以我只是删除了变量,它工作了。

最新更新