Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does require(../) in node.js work?

What modules does node.js look for when it encounters var foo=require(../) ?

It would seem that it would look in the directory one UP from the current one, but what exactly would it look for and do?

Perhaps there is an analogy with include in C or import in Python?

I've been starting with node.js and reading http://nodejs.org/api/modules.html and came upon example code on github such as

var express = require('express')
  , tracker = require('../')

This code would seem to assign variable express contents of express module (file) whose path must be global after using npm to install express, that much seems understandable,although I understand there are two types of module installation, but that is another question.

But what contents are assigned to variable tracker?

like image 702
Sint Avatar asked Jul 06 '26 03:07

Sint


1 Answers

This depends on WHAT is in that directory.

If X begins with './' or '/' or '../':

a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)

LOAD_AS_FILE(X):

  1. If X is a file, load X as JavaScript text. STOP
  2. If X.js is a file, load X.js as JavaScript text. STOP
  3. If X.node is a file, load X.node as binary addon. STOP

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.node is a file, load X/index.node as binary addon. STOP
like image 144
supernova Avatar answered Jul 08 '26 17:07

supernova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!