NodeJS 需要('..')?
NodeJS require('..')?
我一直在查看一些 NodeJS 示例,遇到了以下情况:
var module = require('..');
var module = require('../');
我明白require是干什么的,但是我不明白它这么写是干什么的。有人可以给我解释一下吗?
这是https://nodejs.org/api/modules.html
中定义的规则
require(X) from module at path Y
- If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
由于../
或..
不是文件,它会转到路径B,加载为目录
LOAD_AS_DIRECTORY(X)
- If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c.
LOAD_AS_FILE(M)
- If X/index.js is a file, load X/index.js as JavaScript text. STOP
- If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
- If X/index.node is a file, load X/index.node as binary addon. STOP
根据该规则,它将按顺序检查以下文件
1) ../package.json
2) ../index.js
3) ../index.json
4) ../index.node
如果您需要一个目录,require
将根据这些规则尝试从该目录中包含一个模块:
If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon. STOP
您的目录结构很可能如下所示:
module/
index.js
src/
file-including.js
这将加载 index.js
。您也可以将其写为 require('../index.js')
甚至 require('../index')
,它的功能相同。
使用var module = require('..');
和var module = require('../');
结果相同。
均从父目录加载。
我一直在查看一些 NodeJS 示例,遇到了以下情况:
var module = require('..');
var module = require('../');
我明白require是干什么的,但是我不明白它这么写是干什么的。有人可以给我解释一下吗?
这是https://nodejs.org/api/modules.html
中定义的规则require(X) from module at path Y
- If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
由于../
或..
不是文件,它会转到路径B,加载为目录
LOAD_AS_DIRECTORY(X)
- If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)- If X/index.js is a file, load X/index.js as JavaScript text. STOP
- If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
- If X/index.node is a file, load X/index.node as binary addon. STOP
根据该规则,它将按顺序检查以下文件
1) ../package.json
2) ../index.js
3) ../index.json
4) ../index.node
如果您需要一个目录,require
将根据这些规则尝试从该目录中包含一个模块:
If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon. STOP
您的目录结构很可能如下所示:
module/
index.js
src/
file-including.js
这将加载 index.js
。您也可以将其写为 require('../index.js')
甚至 require('../index')
,它的功能相同。
使用var module = require('..');
和var module = require('../');
结果相同。
均从父目录加载。