There is this concept of Modules in NodeJS, which is kind of but not exactly the same as Class concept of programming languages like Java and ActionScript. To add a module the syntax is
require() // its like import in Java and Actionscript
A detailed implementation of “require()” statement is as below
var myModule = require('./myModule.js');
So that’s all to include a module, if the module JS file and your application JS file are in the same folder, for the time being lets do the understanding this way.
Now lets see what kind of features or flexibility “modules” gives us as a nodeJS developer.
If we think of modules as the Classes then it will be easier for us to understand.
First of all, everything inside a module is private. Ohh yes, private things in javascript. Thats interesting, is not it!
Lets write a simple class kind of thing in a module, which has a private property and getter-setter method of the same.
stupidVar='Global Scope. Avoid this.';// Never put anything in Global Scope
var nameOfModule='I am private';
exports.getName=function(){
return nameOfModule;
}
exports.setName=function(newName){
nameOfModule=newName;
}
Couple of things to note here. First of all every variable that is not declared with “var” is on the Global scope. I think thats true in general for javascript. Apart from this anything else in a module is private, that means the variable “nameOfModule” in our example is only accessible from inside that module itself. If we try to access it from out side the module NodeJS will throw an error. Now to expose methods and properties to outside world, we have to add the methods and properties to an object named “exports”.
Now to consume the module, lets write a “main” class which we can assume as the application entry.
console.log("Hello Modules.");
var modOne=require ('./modOne.js');
console.log(modOne.getName());
modOne.setName("I am set by the setter. Setter is Public.");
console.log(modOne.getName());
//console.log(nameOfModule);// this will throw an ERROR as we are trying to access private var
console.log(stupidVar);
Save both the files in the same directory. Open the commandline and navigate to the directory. To run our application we have to write
node main
Just a note that we do not have to specify “.js” after the “main”, while feeding the file to NodeJS.
The source files for this are here to download.
[reference : net.tutsplus.com ]
Now there are publicly available packages, libraries and modules in our case. To install a module in a nodeJS application, one has to navigate to the folder containing the application through commandline and install the required module. An implementation detail is as below.
npm install module_name
I hope you remember “npm” from previous tutorial. For a quick reminder, “npm” and “node” both the tools are installed by default when we have installed nodeJS. The “npm” is the package manager for nodeJS.
Happy Nodding