简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM