NodeJS require('..')?

岁酱吖の 提交于 2019-12-12 09:49:23

问题


I've been looking through some NodeJS examples and I've encountered the following:

var module = require('..');
var module = require('../');

I understand what require does, but I don't understand what it does when it's written like this. Can somebody explain it to me please?


回答1:


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




回答2:


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.




回答3:


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

Both loaded from the parent directory.



来源:https://stackoverflow.com/questions/42401079/nodejs-require

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