Skip to content

Instantly share code, notes, and snippets.

@fakhrullah
Created January 19, 2017 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fakhrullah/78f1c5fd1cf7a8d5c6b17a48b334ef17 to your computer and use it in GitHub Desktop.
Save fakhrullah/78f1c5fd1cf7a8d5c6b17a48b334ef17 to your computer and use it in GitHub Desktop.

Node.js Module Pattern

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

Resources

Why

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.

Introduction

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