๐Ÿงฐ Node.js File & Server Operations
Estimated reading: 3 minutes 30 views

๐ŸŒ Node.js โ€“ Creating a Web Server โ€“ Step-by-Step Guide Using the http Module


๐Ÿงฒ Introduction โ€“ Why Create a Web Server with Node.js?

Node.js is ideal for building fast, scalable web servers using its non-blocking I/O model. With the built-in http module, you can create a full web server without any external dependencies. This allows you to listen to client requests, send responses, serve pages, and build RESTful APIs from scratch.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to create a basic Node.js web server
  • Handle routing for multiple endpoints
  • Serve HTML content and JSON responses
  • Best practices for error handling and port listening

โš™๏ธ Step 1 โ€“ Load the HTTP Module

const http = require('http');

The http module is built into Node.jsโ€”no need to install anything.


๐Ÿ› ๏ธ Step 2 โ€“ Create the Server

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, world!');
});

๐Ÿ’ก createServer() takes a callback with req (request) and res (response) objects.


๐Ÿš€ Step 3 โ€“ Start Listening on a Port

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

๐Ÿงช Visit http://localhost:3000 in your browser to see the output.


๐Ÿ“ Full Basic Example

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Welcome to my Node.js Web Server!');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

๐Ÿงช Output:

Welcome to my Node.js Web Server!

๐Ÿ“„ Serve HTML Content Instead of Plain Text

const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
  fs.readFile('index.html', (err, data) => {
    if (err) {
      res.writeHead(404);
      res.end('File Not Found');
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    }
  });
}).listen(3000);

๐Ÿ“ Your index.html could contain:

<h1>Hello from HTML!</h1>

๐Ÿ” Add Simple Routing Logic

http.createServer((req, res) => {
  if (req.url === '/') {
    res.end('Home Page');
  } else if (req.url === '/about') {
    res.end('About Page');
  } else {
    res.writeHead(404);
    res.end('404 Page Not Found');
  }
}).listen(3000);

๐Ÿงช Routes:

  • / โ†’ Home Page
  • /about โ†’ About Page
  • Others โ†’ 404 Page Not Found

๐Ÿงฑ Best Practices โ€“ Creating Node.js Web Servers

โœ… Best Practice๐Ÿ’ก Why It Matters
Use Content-Type headersProperly formats text, HTML, or JSON responses
Avoid hardcoding port numbersUse process.env.PORT for deploy flexibility
Add error handling for server/IO opsPrevents app from crashing on file errors
Use async/non-blocking methodsKeeps server performance high

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Youโ€™ve now created a working Node.js web server using the http module. You learned how to serve text, HTML, handle basic routes, and respond to client requests.

๐Ÿ” Key Takeaways:

  • Use http.createServer() to handle requests and send responses
  • Always specify proper content type (text/plain, text/html)
  • Use listen(port) to make your server available
  • Serve HTML files using fs.readFile()

โš™๏ธ Real-world relevance:
Used in custom microservices, REST APIs, landing pages, real-time dashboards, and deployment-ready apps.


โ“FAQs โ€“ Creating a Web Server in Node.js


โ“ Do I need Express to create a web server in Node.js?
โœ… No. You can build a server using only the built-in http module.


โ“ How do I serve different pages in Node.js without Express?
โœ… Use simple if/else conditions to handle different req.url values.


โ“ Can I run the server on a different port?
โœ… Yes. Change server.listen(3000) to any other port like 8000 or use process.env.PORT.


โ“ How do I serve static files (e.g., CSS, JS)?
โœ… You need to use fs.readFile() and handle MIME types manually, or use Express for easier static serving.


โ“ How to stop a running Node.js server?
โœ… Press Ctrl + C in the terminal, or call server.close() in code.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐ŸŒ Node.js โ€“ Creating a Web Server

Or Copy Link

CONTENTS
Scroll to Top