Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

Node.js Module Pattern

A summary of my learning about Node.js module pattern.



I need a note that I can refer about node.js module pattern as I always forgot. I also create this to learn deeper about the node.js module.


Node.js use CommonJS implementation for its module pattern.

In node.js (commonJS), to start use any module we declare require(moduleName) in file where we want to use it.

moduleName here can be:

  • the module name with installed by npm command npm install module
  • reference to file as ./filename.js
  • also accept .json file
// file: main.js

// maindirectory/
// |-- subdir/
// |  |-- mylib.js
// |
// |-- main.js
// |-- mylogger.js

// a module that installed by `npm install` command
var logger = require('winston')

// reference to a file in same dir
var mylogger = require('./mylogger.js')

// reference to a file in sub directory
var anotherModule = require('./subdir/mylib.js')

Module pattern

  1. Simplest way to define a module
  2. Global module - bad because pollute global var
  3. Anonymous function
  4. Named function
  5. Anonymous object
  6. Named object

I will explain the good, the bad, when to use, when to not use, example module use this on every pattern.

If there is no different no good or bad, write why the different?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment