Node.js Web Module
Node.js Web Module
What is Web Server
When we say about the Web Server, this is a software program which handles HTTP requests sent by HTTP clients like web browsers and that will returns web pages in response to the clients. And Web Servers usually respond with html documents along with style sheets, scripts and images.
And when we say about the most of Web Server, these web server support server side scripts by using scripting languages or it can be redirect to application server which perform the specific task of getting data from database, perform complex logic etc. and then sends a result to the HTTP client through the Web Server.
And for exaple we can take Apache Web Server example whcih is commonly used web server. And it is an open source project.
Web Application Architecture
Well web application can be divided in 4 different layers:
- Client Layer:-Here Client layer will mainly contains web browser, mobile browser or application which cna make HTTP request to the web server.
- Server Layer:-Here Server Layer contains Web server which can intercepts the all request made by clients and pass them the response.
- Business Layer:-Well the Business Layer contains application server which is utilized by web server to do required processing.
- Data Layer:-Well the Data Layer contains databases or any source of data.
Creating Web Server using Node.js
Node.js will provides http module and that cen be used to create either HTTP client of server. And we will create a js file which named server.js which is having below code:-
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/');
In next step, we will create a html file named index.html which is having the following code in the same directory where you created server.js
< html>
< head>
< title>Sample Page< /title>
< /head>
< body>
Hello World!
< /body>
< /html>
Now we will open the Node.js command prompt and run the below code:-
Open http://127.0.0.1:8081/index.htm in any browser and see the below result.
| |