文件模块
【File modules】
如果找不到确切的文件名,Node.js 将尝试加载所需的文件名,并依次添加扩展名:.js、.json,最后是 .node。当加载具有不同扩展名的文件(例如 .cjs)时,必须将其完整名称传递给 require(),包括文件扩展名(例如 require('./file.cjs'))。
【If the exact filename is not found, then Node.js will attempt to load the
required filename with the added extensions: .js, .json, and finally
.node. When loading a file that has a different extension (e.g. .cjs), its
full name must be passed to require(), including its file extension (e.g.
require('./file.cjs')).】
.json 文件被解析为 JSON 文本文件,.node 文件被解释为通过 process.dlopen() 加载的已编译插件模块。使用其他扩展名(或根本没有扩展名)的文件将被解析为 JavaScript 文本文件。请参阅 确定模块系统 部分以了解将使用的解析目标。
以 '/' 为前缀的必需模块是指向文件的绝对路径。例如,require('/home/marco/foo.js') 将加载位于 /home/marco/foo.js 的文件。
【A required module prefixed with '/' is an absolute path to the file. For
example, require('/home/marco/foo.js') will load the file at
/home/marco/foo.js.】
以 './' 为前缀的必需模块是相对于调用 require() 的文件的。也就是说,circle.js 必须与 foo.js 在同一目录下,require('./circle') 才能找到它。
【A required module prefixed with './' is relative to the file calling
require(). That is, circle.js must be in the same directory as foo.js for
require('./circle') to find it.】
如果没有以 '/'、'./' 或 '../' 开头来指示文件,该模块必须是核心模块,或者是从 node_modules 文件夹中加载的。
【Without a leading '/', './', or '../' to indicate a file, the module must
either be a core module or is loaded from a node_modules folder.】
如果给定的路径不存在,require() 将抛出 MODULE_NOT_FOUND 错误。
【If the given path does not exist, require() will throw a
MODULE_NOT_FOUND error.】