Building a Simple Web Server with Node.js: A Beginner's Guide
Learn the fundamentals of creating a basic web server using Node.js's `http` module. This tutorial provides a step-by-step guide to building a server that handles HTTP requests and serves static HTML files, perfect for beginners starting with Node.js server-side development.
Building a Simple Web Server with Node.js
Introduction
This tutorial demonstrates creating a basic web server using Node.js's built-in `http` module. Web servers handle HTTP requests from clients (like web browsers) and return responses, typically web pages. This example shows how to create a server that serves a static HTML file.
Understanding Web Servers and Web Application Architecture
A web server is software that responds to HTTP requests. A typical web application might be structured into several layers:
- Client Layer: Web browsers, mobile apps, etc., that make HTTP requests.
- Server Layer: The web server itself (like Apache or Nginx), which receives requests and forwards them.
- Business Layer: Handles application logic and data processing. This might involve an application server or custom code.
- Data Layer: Databases or other data sources.
Creating a Web Server in Node.js
Node.js uses the `http` module to create HTTP servers. This example serves an HTML file named `index.html`.
Creating a Simple Web Server
const http = require('http');
const fs = require('fs');
const url = require('url');
const server = http.createServer(function (request, response) {
const pathname = url.parse(request.url).pathname;
console.log(`Request for ${pathname} received.`);
fs.readFile(pathname.substr(1), function(err, data) {
if (err) {
response.writeHead(404, { 'Content-Type': 'text/html' });
response.write("404 Not Found");
} else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(data.toString());
}
response.end();
});
});
server.listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
Save this as `server.js`.
index.html
<html>
<head><title>Sample Page</title></head>
<body>
<p>Hello World!</p>
</body>
</html>
Create an `index.html` file in the same directory.
Run `node server.js` from your terminal, then open http://127.0.0.1:8081/index.html in a browser.
Conclusion
This simple example demonstrates the basics of building a web server using Node.js. It showcases how to handle requests, read files from the file system, and send responses. This is a starting point for creating more sophisticated web applications.