Sunday 23 December 2012

Node.js Modules

Modules:

       In object oriented programming languages like java, we need to include jar files to get the particular functionality if the native jdk does not provide the same feature.
     In the similarly, Modules provides special features and functionalities.In Node.js we have three types of modules.

  1. Core Modules
  2. custom modules
  3. Third party modules.


These modules, we can install as per our project requirement

To install any core module,

Go to the path of the project,


 type the following command

npm install modulename  -g

here "g" refers to global. If we declare -g, the module will install globally.

Now we will see some basic modules,


File System module:

By using this module, we can read the data from the harddisk.To read data from the file, we need to include file system module.


var fs=require("fs");
console.log("starting  the file");
//fs.readFile(file location,function(error, context)  - for reading the file
//fs.writeFile(file location,function(error, context)  - for writing the file

fs.readFile("path of text file",function(err,data){
   
    console.log("contents in the file",+data);
   
});
console.log("executing in the file");


when we run the program, first it will print starting file. then we it has to load the file, if it ends, it has to call the function. It will print executing in the file while it waiting for the function to load the file.

Now let us see the nodejs.org,

go to FileSystem module,you can find lots of methods available for file system.
You can use any methods.


 
 Web Frameworks:


Routers
Static file servers
frameworks
microframeworks
Middleware



Routers:

connect-route: A simple router for connect.

How to install?

npm install connect-route -g


How to use:

See this example
var connect = require("connect");
var connectRoute = require("connect-route");

connect(
  connect.static(dirname + "/public"),
  connectRoute(function(app) {
    app.get("/hello", function(req, res) {
        html = "<!doctype html>" +
          "<html><head><title>Hello  MobEngineers</title></head>" +
          "<body><h1>Hello Mob Engineers</h1></body></html>";

      res.end(html);
    });
  })
).listen(8008);


0 comments:

Post a Comment