Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS require('..')?

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?

like image 803
user1157885 Avatar asked Feb 22 '17 19:02

user1157885


1 Answers

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

like image 164
Anthony C Avatar answered Oct 12 '22 19:10

Anthony C