node.js web server module
What is web server ?
Web servers can refer to hardware or software or both of them working together.Web servers are computers that are usually setup in facilities called Data Centers and operated by hosting companies.The files stored on web servers are read by browsers.Browsers communicates with web servers to bring you information from internet.
Purpose of Web server
- Store website so that people can visit them on internet.
- It serves file as per request.
- It can send same or different file to one or more than one user at the same time.
Now our level has gone high and today we are discussing our first "Hello World" web application.
for this purpose I have to create two files
- index.html : which display on browser after server is started.
- server.js : before running our first application on browser server should be started and that will be done by server.js.
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// Write the content of the file to response body
response.write(data.toString());
}
// Send the response body
response.end();
});
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
After that open cmd and type command
node server.js
Hello Word!
http://127.0.0.1:8081/index.html
and you will obtain this output
Comments
Post a Comment