Advanced Example 1: Building a Custom HTTP Server with Node.js 🌐
This example demonstrates how to create a simple HTTP server using Node.js, handling GET requests and serving dynamic content.
Step-by-Step Guide
Initialize a new project
Runnpm init -y
to create apackage.json
file.Create the server file
Save the following code asserver.js
:
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/hello') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World! 🎉');
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found 😢');
}
}).listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
- Run the server
Executenode server.js
and navigate tohttp://localhost:3000/hello
in your browser.
Key Features
- ✅ Handles GET requests
- 📁 Serves static/dynamic content
- 🌐 Works with Node.js
For more advanced topics, check out our Advanced Topics documentation.