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!
Top comments (11)
I really love it when the fundamentals are being taught before jumping into frameworks like express.
Thanks
True
I appreciate the education here about Node.js basics but there are also quite some security issues with the above code. It's functional, sure, but also vulnerable, so worth calling out 😅
I'm doing a lot of work to educate developers on secure coding practices in Node.js (via nodejs-security.com/) so I am sensitive to these sort of tutorials.
Nice to not jump immediately into frameworks
You explained with great explanation, Thankyou
try express.
There is a high chance if he can write a plain
htmlhttp server he can do it with express too.However this approach is much much better than using express (with some drawbacks yes). e.g. this is a module leas script. It means there is no package manager, no node_modules etc. its a plain script you can just node script.js to run with little overhead. Not to forget the immense control because of the barebones nature of this approach as well. The obvious con is performance and developer experience.
Try being a new dev again.
Next Part -> PART - 6
Join this group for more updates : FullStackLearners