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')
- Simplest way to define a module
- Global module - bad because pollute global var
- Anonymous function
- Named function
- Anonymous object
- 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?