简体   繁体   English

Node.js 要求本地文件抛出错误

[英]Node.js require local file throws an error

This is my project's filesystem.这是我项目的文件系统。

root
index.js
package.json
...etc
commamds
- ping.js
- eval.js
- ...etc

This is a normal discord.js bot.这是一个普通的 discord.js 机器人。 But when I try reloading the commands, I use the following code:但是当我尝试重新加载命令时,我使用以下代码:

...etc
let pull = require(`./${file}`);
// file is command files from fs.readdirSync() and it can be 'ping.js', 'eval.js', ...
...etc

But it throws a referenceerror that the module can't be found.但它会抛出一个找不到模块的参考错误。 But when I try fs.readFile(), it works.但是当我尝试 fs.readFile() 时,它起作用了。 What's the problem?有什么问题?

fs.readFile() defaults to the current working directory if there is no path or if there's a relative path on the filename.如果没有路径或文件名上有相对路径,则fs.readFile()默认为当前工作目录。

require() has a completely separate set of rules for where it looks for files. require()有一套完全独立的规则来查找文件。 For example, a filename with no path at all looks in the node_modules directory and in the global module location(s).例如,一个完全没有路径的文件名在node_modules目录和全局模块位置中查找。 A filename starting with ./ looks in the current module's home directory../开头的文件名在当前模块的主目录中查找。 And so on... It's a different set of rules than fs.readFile() .等等......这是一组与fs.readFile()不同的规则。

Since you don't show us what file actually is, it's hard to know precisely, but perhaps you need to combine the filename with the appropriate path so you are giving require() a full path name and it will go exactly there, not use the normal rules for where require() looks when given only a plain filename.由于您没有向我们展示实际是什么file ,因此很难准确知道,但也许您需要将文件名与适当的路径组合起来,因此您为require()提供了一个完整的路径名,它将 go 准确地存在,不使用当只给定一个普通文件名时,其中require()的正常规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM