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?
This is the rule defined in 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)
Since ../
or ..
is not a file, it will go to path B, to load as directory
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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With