HTTP Module and Creating Server in Node.js
HTTP Module and Creating Server in Node.js Explained
The HTTP module and creating server in Node.js is a core concept in backend development. The HTTP module in Node.js allows you to build web servers that can handle client requests and send responses. Understanding the HTTP module and creating server in Node.js is essential for learning how backend systems work.
What is HTTP Module in Node.js
The HTTP module in Node.js is a built-in module used to create servers and manage HTTP requests and responses. It does not require installation and is available by default in Node.js.
Import HTTP Module in Node.js
Syntax
const http = require(‘http’);
You must import the HTTP module in Node.js before creating a server.
Create Server in Node.js
Basic Server Example
const http = require(‘http’);
const server = http.createServer((req, res) => {
res.write(‘Hello from Node.js Server’);
res.end();
});
server.listen(3000, () => {
console.log(‘Server running on port 3000’);
});
This example shows how the HTTP module and creating server in Node.js works.
Understanding Request and Response
Request Object
The request object contains data sent by the client such as URL, method, and headers.
Response Object
The response object is used to send data back to the client.
Example
const http = require(‘http’);
const server = http.createServer((req, res) => {
console.log(req.url);
res.end(‘Response sent’);
});
server.listen(3000);
Routing in Node.js using HTTP Module
Example of Routing
const http = require(‘http’);
const server = http.createServer((req, res) => {
if (req.url === ‘/’) {
res.end(‘Home Page’);
} else if (req.url === ‘/about’) {
res.end(‘About Page’);
} else {
res.end(‘Page Not Found’);
}
});
server.listen(3000);
This shows how different routes are handled in Node.js.
Setting Headers in Node.js
Example
res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
Headers help define the type of response sent to the client.
Run Node.js Server
Command
node app.js
Open browser and visit http://localhost:3000
Best Practices
Use Proper Status Codes
Always send correct HTTP status
Keep Code Clean
Write simple and readable server logic
Use Frameworks
Use Express.js for large applications
Real-World Use
The HTTP module and creating server in Node.js is used to build APIs, web servers, and backend services. It is the foundation of backend development.
FAQs on HTTP Module in Node.js
What is HTTP module in Node.js
It is used to create servers and handle requests
How to create server in Node.js
Use http.createServer method
Is HTTP module enough
It is basic, Express.js is preferred for large apps
Continue Learning Backend Development
Now that you understand HTTP module and creating server in Node.js, you can move to Express.js framework for advanced backend development. To explore more structured tutorials and courses, click here for more free courses.



