What is Web Module in Node.js?
Web module in Nodejs is responsible to handle the HTTP web requests, by using web server and web reources.
web server:
Webserver handle the HTTP requests process them with specific tasks like (interaction with databases, filesystems..) and sends the response as a web resources or result data.
Web resources:
These are the asstes or files like documents , images, style sheets, and scripts which a web server return in form of response from their end.
Web Module application architecture:
Applications are built in 4 layers:
Client -
It sends requests to the web server and gets the response
Web Server -
It receives requests and then interact with Business layer to get response
Business Layer -
It receives requests from server and then interact with data layer to get response
Data Layer -
It receives requests from Business Layer and then run query to get the response form the data storages and response back to business layer.
Now lets have a look step by step, how to create a web server in Node.js
Step 1:
Create a js file named server.js in root:
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "index.html" + q.pathname;
fs.readFile(filename, function (err, data) {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end("404 Not Found");
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8000);
console.log('server running at localhost:8000');
Step 2:
Create an HTML file named index.html in the same directory where you have created the server.js and add the below code.
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to DritalConnect!</h1>
</body>
</html>
Step 3:
Open the Node.js command prompt and run the following commands:
node server.js
Step 4:
Verify Output:
Open the browser and type the URL
http://localhost:8000/index.html
Check your output in browser - Welcome to DritalConnect!