NodeJS Module Loading


I was wondering, how nodejs resolves a module, when we write a code like var foo = require('moduleName'). After reading and doing some analysis I came to know following execution path for the module loading.

If moduleName is a Core Module

NodeJS provides many core modules like fs, path, cluster etc.. If moduleName is any of the core module name, load it.

If moduleName starts with ./, ../ or /

  • Load As File
    • If moduleName is a file, load it as a javascript file
    • If moduleName is a file with .js extension, load it as a javascript file
    • If moduleName is a file with .json extension, parse that to javascript object
    • If moduleName is a file with .node extension, load that as a binary addon
      • Binary Addons are dynamically-linked shared objects and provide glue to C and C++ libraries.
  • Load As Directory
    • If moduleName is a directory and that directory has a package.json file, then look for “main” field in that json file, and try to load the file mentioned in “main” field, using above algorithm
    • If moduleName/index.js exists, load it
    • If moduleName/index.json exists, parse it to a json object
    • If moduleName/index.node exists, load it as a binary addon

Else,

  • Try to find module in NODE_PATH environment variable
    • We can give multiple paths delimited by semicolons on Windows, and by colons in UNIX systems.
  • Try to find module at node_modules folders
    • Start finding module at path = parentDirectory/node_modules.
    • If not found on above path, go up one directory level and continue going up one level, untill root folder of the file system is reached.
    • If not found at any of the above paths, then try to find at, $HOME/.node_modules, $HOME/.node_libraries or $PRIFIX/lib/node.
      • It is preferable to do not depend on module loading from $HOME/.node_modules, $HOME/.node_libraries or $PREFIX/lib/node. As these are there for some historic reasons and may be deprecated in future. It is always preferable to keep the module dependencies nearer to the project.
    • Example,
      • If require(‘foo’) is written in projects/nodejs/practice/bar.js file, then it will try to find foo module as a directory or a file at below places:
        /projects/nodejs/practice/node_modules/foo
        /projects/nodejs/node_modules/foo
        /projects/node_modules/foo
        /node_modules/foo
        /Users/userName/.node_modules/foo
        /Users/userName/.node_libraries/foo
        /usr/local/lib/node/

Menu