NodeJS require('..')?

白昼怎懂夜的黑 提交于 2019-12-06 01:18:43

This is the rule defined in https://nodejs.org/api/modules.html

require(X) from module at path Y

  1. If X begins with './' or '/' or '../'
    a. LOAD_AS_FILE(Y + X)
    b. LOAD_AS_DIRECTORY(Y + X)

Since ../ or .. is not a file, it will go to path B, to load as directory

LOAD_AS_DIRECTORY(X)

  1. 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

By that rule, it will check the following files in this order

1) ../package.json

2) ../index.js

3) ../index.json

4) ../index.node

If you require a directory, require will try to include a module from that directory based on these rules:

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

Most likely you have a directory structure that looks like this:

module/
  index.js
  src/
    file-including.js

This will load index.js. You could also write it as require('../index.js') or even require('../index') and it would function the same.

Use var module = require('..'); and var module = require('../'); results the same.

Both loaded from the parent directory.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!