Hey there, awesome devs! π Have you ever wondered how web servers work? What if I told you that you can create your own server in just a few lines of JavaScript? π€―
With Node.js, you donβt need a fancy framework to build a basic server. The built-in HTTP module lets you create a web server that can handle requests and send responsesβjust like a real web app! π‘
In this blog, weβll go step by step to build a simple Node.js server. By the end, youβll understand how servers work and feel like a backend ninja! π₯·π₯
π What is a Web Server?
A web server is a program that listens for requests from a client (like a browser) and responds with data (like an HTML page or JSON). It acts as the middleman between users and your website.
β
When you visit example.com
, your browser sends a request to a web server.
β
The server processes the request and sends back a response (HTML, JSON, files, etc.).
β
Your browser displays the response, and voilΓ ! π
Now, let's build our own server! ποΈ
π Step 1: Setting Up Your Project
First, make sure you have Node.js installed. You can check by running:
node -v
If Node.js is installed, you'll see a version number. If not, download it from nodejs.org. β
Create a new project folder and navigate to it:
mkdir my-node-server && cd my-node-server
Now, let's create our server file:
touch server.js
ποΈ Step 2: Creating a Basic Node.js Server
Now, open server.js
and add the following code:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world! π');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000 π');
});
β How it works:
- We import the
http
module. - We use
http.createServer()
to create a server. - When a request comes in, we send a plain text response.
- The server listens on port 3000.
Run the server with:
node server.js
Now, open your browser and visit http://localhost:3000
βyou should see "Hello, world!" π
π‘ Step 3: Handling Different Routes
A real web server should respond differently based on the URL (route). Let's modify our server to handle multiple routes:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (req.url === '/') {
res.end('Welcome to the Home Page! π ');
} else if (req.url === '/about') {
res.end('About Us Page π');
} else {
res.writeHead(404);
res.end('404 Not Found β');
}
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000 π');
});
β Now try:
-
http://localhost:3000/
π (Home page) -
http://localhost:3000/about
π (About page) -
http://localhost:3000/contact
β (Oops! 404 error)
π₯οΈ Step 4: Sending an HTML Response
Instead of plain text, let's send HTML:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Welcome to My Node.js Server! π</h1>');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000 π');
});
β
Now, visiting http://localhost:3000
will display styled HTML content! π¨
π₯ Step 5: Serving JSON (for APIs)
Let's modify our server to respond with JSON data instead:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
const data = { message: 'Hello, this is JSON data! π' };
res.end(JSON.stringify(data));
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000 π');
});
β
Now, visiting http://localhost:3000
will return JSON dataβgreat for building APIs! π‘
π― Conclusion
Boom! You just built a fully functional Node.js server from scratch! π Now, you understand how web servers work and can start building real-world applications!
π Recap:
- Created a simple Node.js server with the HTTP module.
- Handled multiple routes (Home, About, 404 errors).
- Sent HTML and JSON responses for different use cases.
- Learned how web servers work under the hood.
In the next article, weβll explore JSON Response, Stay tuned! π₯
If you found this blog helpful, make sure to follow me on GitHub π github.com/sovannaro and drop a β. Your support keeps me motivated to create more awesome content! π
Happy coding! π»π₯
Top comments (1)
This is very good, but you can inherit from Server for Http protocol and handle it better.
(not good for production environment)