Node - Module (ie NPM Module)


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)



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.

Built-In Core

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



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

// Prints: /Users/mjr/example.js


// Prints: /Users/mjr


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

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));

Documentation / Reference

Task Runner