๐Ÿงฐ Node.js File & Server Operations
Estimated reading: 3 minutes 276 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 :
Share

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

Or Copy Link

CONTENTS
Scroll to Top