HTML or File call in Node.js


Before to Start please read the 3_Http_Request Doc. This is use to read a html file which is in our disk. push in to browser according to client request.

var http = require("http");
// Import File system module to read the file
var file = require("fs");

console.log("Starting");

var host = "127.1.1.1";
var port = 1337;

/* Creating a callback which fired every single request that contain the url from client request and response is similar as request*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);

//After we receive the file then we have to read the file from the request URL
file.readFile("." + request.url,
function(error,data){
/* Here we have error object and Data Object in function. So error and data can be return to that specific variables. Therefore If we have error we have to respond to user with predefined String else we have to return the file*/
if(error){
//404 is the status code for not found
response.writeHead(404,{"Content-type":"text/plain"}); response.end("Sorry the page was not found");
}else{

//here our file system is Html so the content type is html
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After the code completes,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1337/name.html
4) you will get the result as html page or error message depend on the request in browser.


1 comment:

  1. impressive blog , keep post and if you are intresting in software developer, java developer then check out java course in satara

    ReplyDelete