文件模块


如果找不到确切的文件名,Node.js 将尝试加载所需的文件名,并添加扩展名:.js.json,最后是 .node。 当加载具有不同扩展名的文件(例如 .cjs)时,则必须将其全名传给 require(),包括其文件扩展名(例如 require('./file.cjs'))。

.json 文件被解析为 JSON 文本文件,.node 文件被解释为加载了 process.dlopen() 的已编译插件模块。 使用任何其他扩展名(或根本没有扩展名)的文件被解析为 JavaScript 文本文件。 请参阅确定模块系统章节以了解将使用什么解析目标。

'/' 为前缀的必需模块是文件的绝对路径。 例如,require('/home/marco/foo.js') 将在 /home/marco/foo.js 加载文件。

'./' 为前缀的必需模块与调用 require() 的文件相关。 也就是说,circle.js 必须和 foo.js 在同一个目录下,require('./circle') 才能找到它。

如果没有前导 '/''./''../' 来指示文件,则该模块必须是核心模块或从 node_modules 文件夹加载。

如果给定路径不存在,则 require() 将抛出 MODULE_NOT_FOUND 错误。

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 files are parsed as JSON text files, .node files are interpreted as compiled addon modules loaded with process.dlopen(). Files using any other extension (or no extension at all) are parsed as JavaScript text files. Refer to the Determining module system section to understand what parse goal will be used.

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.

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.

Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.

If the given path does not exist, require() will throw a MODULE_NOT_FOUND error.