6

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?

user1157885
  • 1,999
  • 3
  • 23
  • 38

3 Answers3

5

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

Anthony C
  • 2,117
  • 2
  • 15
  • 26
  • hi. i'm wondering. what is it happening when i do like this. please see this repo (https://github.com/MJB-Khorasani/require) and answer me. thanks. in admin.js file & user.js file it does not know express. but i import it in imports.js file. so what's wrong with this? – Kasir Barati Feb 18 '20 at 16:33
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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

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

Both loaded from the parent directory.

  • hi. i'm wondering. what is it happening when i do like this. please see this repo (github.com/MJB-Khorasani/require) and answer me. thanks. in admin.js file & user.js file it does not know express. but i import it in imports.js file. so what's wrong with this? – Kasir Barati Feb 20 '20 at 10:22