Node - Module (ie NPM Module)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > Node.js > Node - Module (ie NPM Module)

1 - About

The module notion in Node.

A module in Node is the source script (not the bundled library/package).

The module loader of Node use the commonJs format. Therefore a commonJS Module will run in Node.

A package is a bundle of one or more module.

Each file is treated as a separate module. (One Module has one file)

Advertising

3 - Property

3.1 - Scope

A module has its own scope, unless you decide to expose functionality using exports or module.exports

Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper).

In Node.js this is different. The top-level scope is not the global scope

  • within the browser var something is defined a new global variable
  • inside a Node.js module, var something will be local to that module.

3.2 - Built-In Core

Node.js has several modules compiled into the binary called the core module

3.3 - FileName

See https://nodejs.org/api/globals.html#globals_filename

__filename is not actually a global but rather local to each module.

console.log(__filename);
// Prints: /Users/mjr/example.js

3.4 - Directory

console.log(__dirname);
// Prints: /Users/mjr

4 - Implementation

The module system is implemented in the require('module') module.

5 - Is this a node environment

console.log("Is this a Node environment ?: "+(typeof exports === 'object' && typeof module !== 'undefined'));
console.log("Is this a Node environment ?: "+(typeof module === 'object' && module.exports));

Advertising

6 - Documentation / Reference

web/javascript/node/module/module.txt · Last modified: 2019/05/25 14:13 by gerardnico