Tuesday, June 30, 2015

Modules in node js (Scope and design patterns)

Scope in nodejs: 
Setting proper scope of the variable is important in JavaScript and same is applicable to node. We should avoid using global variable in node js since there may be collision in variables.

When we import a module, it caches the module, which is good thing. But, sometimes it may cause problem.

For example: In following module if we set "values" as a global variable, then last object value to global variable will be set and it will override the previous object values.


  1. Declare private variable in module that you do not want to expose
  2. Copy all the property of argument into private variable
  3. Return the public function from module that you want to export. we can now use private variable inside public function and return it. 

Factory design pattern in node.js:
Now, we can see that correct object is created by updating the scope. But, this is probably not a correct way to create module. We should take help of constructor to create object.

So, create a constructor Project and use this to declare all the public variables and functions.
We can also create instance in "module.exports" which can act as factory. we can pass a type and based on the type a constructor can be called. Creating instance at run-time with above method is known as factory pattern.

If we do not wish to create factory design pattern, we can simply assign "Project" to module.exports.
This way we can create instance later as per our need and set or get values.