Express module in Node.js


Express is the high performance and high class web development module package for Node . Which will process on top of the HTTP module and call the http class. Therefore we can create website with less of an effort and clean.

To install express module,
npm install express in linux terminal.

use npm list command to check what are the module listed in your on your project. Check the update of the module because according to the update the class calling method can be vary. For example,

Express older version: var app = express.createServer();
Express newer version: var app = express();

So this kind of change mentioned in module doc.

Sample Code :

var file = require("fs");
var config = JSON.parse(file.readFileSync("config.json"));
var host = config.host;
var port = config.port;

//include the express module
var express = require('express');
var app = express();

//check the original route path
app.use(app.router);

//express the static file location (Say if we have our html file in public folder)
app.use(express.static(__dirname + "/public"));

app.get("/", function(request, response){
//Sending the response to client
response.send('hello world');
});

/*Any URl come with /hello/ then we can redirect to our public directory here we print the text which is continue with /hello/ */
app.get("/hello/:text",
   function(request,response){
       response.send("hello" + request.params.text);
   }
);
//file format similar to JSON format
var users = {
       "1" : {
               "name" : "user 1",
               "Social" : "user 1 link"
               },
       "2" : {
               "name" : "user 2",
               "Social" : "user 2 link"
               }
};

/*Getting the user by ID. Here we search in broweer as 127.1.1.1:1336/user/1 because our host is 127.1.1.1 and port is 1336*/
app.get("/user/:id",
   function(request,response){
       var user = users[request.params.id];
       if(user){
        response.send("<a href://faceboo.com>" + user.Social + "view me " + user.name+"</a>");
       }else{
           response.send("Sorry! User not found",404);
       }

   }
);


app.listen(port,host);

1)run the .js file using node extension
2) call the user id with hello/id

NOTE:config.json file contain the host and port address .see the doc

1 comment: