Part 5: Building a Simple Web Server with Node.js

RMAG news

In the previous articles, we explored Node.js fundamentals, setting up your environment, and how to work with Node.js modules. Now, we’re going to put that knowledge into practice by building a simple web server. This practical application will consolidate your understanding and showcase the power of Node.js in handling web requests.

Step 1: Review of the HTTP Module

We briefly touched on the http module in our discussion about built-in modules. It’s a core Node.js module used to create HTTP servers. Here’s a quick recap:

const http = require(http);

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(Content-Type, text/plain);
res.end(Hello, World!n);
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});

Step 2: Expanding Our Server

Now, let’s enhance our server by handling different routes and serving static files.

Handling Routes

We can handle different routes by checking the URL in the request object. Let’s add a simple routing mechanism:

const http = require(http);

const server = http.createServer((req, res) => {
if (req.url === /) {
res.statusCode = 200;
res.setHeader(Content-Type, text/html);
res.end(<h1>Welcome to Our Home Page</h1>);
} else if (req.url === /about) {
res.statusCode = 200;
res.setHeader(Content-Type, text/html);
res.end(<h1>About Us</h1>);
} else {
res.statusCode = 404;
res.setHeader(Content-Type, text/html);
res.end(<h1>Page Not Found</h1>);
}
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});

Serving Static Files

To serve static files like HTML, CSS, and JavaScript, you can create a function to read file contents and send them in the response:

const http = require(http);
const fs = require(fs);
const path = require(path);

const server = http.createServer((req, res) => {
let filePath = path.join(__dirname, public, req.url === / ? index.html : req.url);

const ext = path.extname(filePath);
let contentType = text/html;
switch (ext) {
case .css:
contentType = text/css;
break;
case .js:
contentType = text/javascript;
break;
case .json:
contentType = application/json;
break;
// Add more cases for other file types if needed
}

fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === ENOENT) {
// Page not found
fs.readFile(path.join(__dirname, public, 404.html), (err, content) => {
res.writeHead(404, { Content-Type: text/html });
res.end(content, utf-8);
});
} else {
// Some server error
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
// Success
res.writeHead(200, { Content-Type: contentType });
res.end(content, utf-8);
}
});
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});

Conclusion

Building a web server with Node.js is straightforward thanks to its powerful core modules. By handling routes and serving static files, you’ve taken significant steps toward developing full-fledged web applications. In the next part of our series, we’ll explore how to integrate external libraries and frameworks to further enhance your server’s capabilities.

Stay tuned for more advanced Node.js development techniques!

Leave a Reply

Your email address will not be published. Required fields are marked *