Skip to content

Instantly share code, notes, and snippets.

@simlegate
Created March 18, 2016 11:14
Show Gist options
  • Select an option

  • Save simlegate/7ca5a3ac6c6492611133 to your computer and use it in GitHub Desktop.

Select an option

Save simlegate/7ca5a3ac6c6492611133 to your computer and use it in GitHub Desktop.

Revisions

  1. simlegate revised this gist Mar 18, 2016. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions node-module-require
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    From https://nodejs.org/api/modules.html

    require(X) from module at path Y
    1. If X is a core module,
    a. return the core module
  2. simlegate revised this gist Mar 18, 2016. No changes.
  3. simlegate created this gist Mar 18, 2016.
    41 changes: 41 additions & 0 deletions node-module-require
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    require(X) from module at path Y
    1. If X is a core module,
    a. return the core module
    b. STOP
    2. If X begins with './' or '/' or '../'
    a. LOAD_AS_FILE(Y + X)
    b. LOAD_AS_DIRECTORY(Y + X)
    3. LOAD_NODE_MODULES(X, dirname(Y))
    4. THROW "not found"

    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.json is a file, parse X.json to a JavaScript Object. STOP
    4. 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.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

    LOAD_NODE_MODULES(X, START)
    1. let DIRS=NODE_MODULES_PATHS(START)
    2. for each DIR in DIRS:
    a. LOAD_AS_FILE(DIR/X)
    b. LOAD_AS_DIRECTORY(DIR/X)

    NODE_MODULES_PATHS(START)
    1. let PARTS = path split(START)
    2. let I = count of PARTS - 1
    3. let DIRS = []
    4. while I >= 0,
    a. if PARTS[I] = "node_modules" CONTINUE
    c. DIR = path join(PARTS[0 .. I] + "node_modules")
    b. DIRS = DIRS + DIR
    c. let I = I - 1
    5. return DIRS