文件模块
如果找不到确切的文件名,Node.js 将尝试加载所需的文件名,并添加扩展名:.js
、.json
,最后是 .node
。
.js
文件被解释为 JavaScript 文本文件,而 .json
文件被解析为 JSON 文本文件。
.node
文件被解释为加载了 process.dlopen()
的编译插件模块。
以 '/'
为前缀的必需模块是文件的绝对路径。
例如,require('/home/marco/foo.js')
将在 /home/marco/foo.js
加载文件。
以 './'
为前缀的必需模块与调用 require()
的文件相关。
也就是说,circle.js
必须和 foo.js
在同一个目录下,require('./circle')
才能找到它。
如果没有前导 '/'
、'./'
或 '../'
来指示文件,则该模块必须是核心模块或从 node_modules
文件夹加载。
如果给定的路径不存在,则 require()
将抛出 Error
,其 code
属性设置为 '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
.
.js
files are interpreted as JavaScript text files, and .json
files are
parsed as JSON text files. .node
files are interpreted as compiled addon
modules loaded with process.dlopen()
.
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 an Error
with its
code
property set to 'MODULE_NOT_FOUND'
.