Building a Simple Web Server in Node.js: A Beginner's Guide
Ann Mukami
Posted on May 6, 2024
Are you curious about how websites work behind the scenes? Have you ever wondered what happens when you type a URL into your browser and hit enter? In this beginner-friendly guide, we'll explore the basics of building a simple web server using Node.js, a popular JavaScript runtime.
Setting up the Tools
Before we dive into building our web server, let's gather the tools we'll need:
const http = require('http');
const fs = require('fs');
const url = require('url');
const querystring = require('querystring');
const figlet = require('figlet');
Creating a Server#
Now, let's create our web server using Node.js's built-in http
module:
const server = http.createServer((req, res) => {
// Server code here
});
This code sets up a server that listens for incoming requests and defines what to do when a request is received.
Reading Requests#
When a request comes in, we need to understand what the requester is asking for:
const page = url.parse(req.url).pathname;
const params = querystring.parse(url.parse(req.url).query);
Here, we're parsing the URL to extract the path and any query parameters that might be included in the request.
Checking What's Asked For#
Based on what the requester wants, we respond accordingly:
if (page == '/') {
// Send main page
} else if (page == '/otherpage') {
// Send other page
} else if (page == '/api') {
// Deal with API request
} else {
// Handle 404 error
}
We check the path of the request and take appropriate actions, such as serving different pages or handling API requests. If the requested page doesn't exist, we send a "404 Not Found" error message.
Sending Back the Response
Once we know what the requester wants, we send back the response:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
We set the appropriate HTTP status code (e.g., 200 for "OK") and send the requested data back to the requester.
Dealing with Different Requests#
Sometimes, the requester may ask for something we don't have:
figlet('404!!', function(err, data) {
res.write(data);
res.end();
});
In this case, we use the figlet module to create an ASCII art representation of "404!!" and send it back as an error message.
Listening All the Time#
Finally, we need our server to listen for requests continuously:
server.listen(8000);
This line of code tells our server to listen on port 8000 for incoming requests, making our web server always available.
And there you have it! With just a few lines of code, we've created a simple web server in Node.js. While this example is basic, it provides a foundation for understanding how web servers work and can serve as a starting point for more complex applications. Happy coding!
Posted on May 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.