- Oct 01, 2018
- admin
- 0
Node.js Web Server:
A software program that handles the HTTP requests sent by web applications, is called as Web Server. A web server responds with html documents or web pages to the HTTP clients.
Web Application Architecture:
| LAYER | DESCRIPTION |
| Client Layer | Contains web and mobile applications that sent HTTP request to the web server. |
| Server Layer | Contains Web server to intercept the requests sent by web applications and usually responds with html documents. |
| Business Layer | Contains application server that interacts with the data layer and is also utilized for processing by server layer. |
| Data Layer | Contains databases and other data sources. |
To Create Node.js Web Server:
- Import the http module using require() function.
- Call the createServer() method with specified request and response parameter.
- Call the listen() method with specified port number.
- Type the command node server.js in command prompt.
- Create the required html file in the same folder as server.js.
- Open the link displayed in the command prompt message with the html filename added at the end of the link in any browser.
Example:
//Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
http.createServer( function (request, response)
{
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data)
{
if (err)
{
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
}
else
{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
//Example.html
<html> <head> <title>Example</title> </head> <body> Hello Tech Tutorialz! </body> </html> OUTPUT:
// At Command Prompt:
Server running at http://127.0.0.1:8080/
Request for /example.html received.
// At Browser link — http://127.0.0.1:8080/example.html:
Hello Tech Tutorialz!
Tags: Node.JS Web Server, NodeJS Tutorial