CommonJs (NodeJs) - Require

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

1 - About

The import statement implementation in commonjs

require() is the built-in statement from the commonjs module format to load module|module.

Counter part of Javascript - Import

require returns a value, depending on what the commonJs module exposes using exports or module.exports

require is one way to import a module in Javascript. In the Javascript specification, it's equivalent to the import statement

Node.js follows also the commonJs format

Advertising

3 - Syntax and High-level algorithm of require in Node

The below require statement called from a module located at path Y

require(X) 

where:

Require will resolve the module location with the following algo:

  • 1. If X is a core module,
  • 2. If X begins with /
    • a. set Y to be the filesystem root
  • 3. If X begins with ./ or / or ../, it indicates:
  • 4. otherwise try to load from a node_modules folder.: LOAD_NODE_MODULES(X, dirname(Y))
  • 5. THROW “not found”

More .. see high-level algorithm in pseudocode of what require.resolve() does

Advertising

3.1 - Dependency Cycle

3.2 - Module File Extension

If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions:

  • .js (interpreted as JavaScript text files)
  • .json (parsed as JSON text files)
  • and finally .node. (interpreted as compiled addon modules loaded with dlopen)

4 - Example

4.1 - Node Module

Local Package installed with Node - npm cli (Node package manager)

var demo=require('package-name');
 
demo.printMsg

4.2 - Project Module

circle.js
const { PI } = Math;
 
exports.area = (r) => PI * r ** 2;
 
exports.circumference = (r) => 2 * PI * r;
  • The client of the modules> By giving the path, node know that it's a project module
foo.js
//  loads the module circle.js that is in the same directory as foo.js.
const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
Advertising
web/javascript/require.txt · Last modified: 2019/03/19 09:16 by gerardnico