我尝试在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; } });
错误:
/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
。
该错误意味着您尝试在执行此范围内的
fs
或 const fs = ...
定义之前使用变量 let fs = ...
。与 var
(定义在内部提升)不同,您不能在用 let
或 const
声明变量之前使用变量。
根据我们可以看到的代码位,我猜您是在
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
当您运行此程序时,它会给出以下错误:
ReferenceError: Cannot access 'fs' before initialization
或者,类似地,如果您在包含
fs
语句的同一函数中的其他位置定义 switch
,但在 switch
语句之后。这也会导致同样的问题。
就我而言,这是因为我有一个名为
const process = null
的变量导致 node.js 进程被覆盖。
所以我只是删除了变量并且它起作用了。