โš™๏ธ Node.js Core Concepts & Features
Estimated reading: 4 minutes 33 views

๐ŸŒ Node.js โ€“ Web Module โ€“ Create HTTP Servers Using Built-In http and https Modules


๐Ÿงฒ Introduction โ€“ What Is the Web Module in Node.js?

Node.js comes with built-in support for web development through the http and https modules. These core modules let you create full-featured web servers, handle routing, serve HTML content, and respond to HTTP requestsโ€”all without needing third-party frameworks like Express.

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

  • How to create HTTP and HTTPS servers using Node.js
  • Handle GET, POST, and other request methods
  • Serve files and send responses
  • Compare http with Express.js (optional upgrade path)

๐Ÿงฐ The http Module โ€“ Create Basic Web Server

The http module lets you build a web server that listens for requests and sends responses.

โœ… Example โ€“ Simple HTTP Server

const http = require('http');

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

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

๐Ÿงช Output (Browser/Terminal):

Hello from Node.js Web Server!

๐Ÿ”„ Handling Different Routes

const http = require('http');

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 Not Found');
  }
}).listen(3000);

๐Ÿงช Visiting:

  • / โ†’ “Home Page”
  • /about โ†’ “About Page”
  • /xyz โ†’ “404 Not Found”

๐Ÿ“ฉ Handling POST Requests (With Body)

const http = require('http');

http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', chunk => (body += chunk));
    req.on('end', () => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`Received POST data: ${body}`);
    });
  } else {
    res.end('Send a POST request');
  }
}).listen(3000);

๐Ÿงช POST with data: "name=NodeJS"
๐Ÿงช Response:

Received POST data: name=NodeJS

๐Ÿ”’ https Module โ€“ Create Secure Server (SSL)

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

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Secure Server');
}).listen(443);

๐Ÿ›ก๏ธ Requires SSL certificate files: key.pem and cert.pem.


๐Ÿ“„ Serving Static HTML File

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

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);

๐Ÿงช Visiting localhost:3000 loads index.html.


๐Ÿ“ฆ http Module โ€“ Key Methods & Properties

Method / PropertyDescription
createServer()Creates a new web server instance
req.methodHTTP method (GET, POST, etc.)
req.urlURL path of the incoming request
res.writeHead()Set status code and headers
res.end()Send the response and close connection

โš–๏ธ http vs Express โ€“ Quick Comparison

Featurehttp (Core Module)Express.js (Framework)
RoutingManual if/else blocksBuilt-in routing system
MiddlewareNot availableFull middleware support
File ServingManual using fsexpress.static() support
PerformanceFaster (bare metal)Slight overhead with features
Use CaseSmall tools, custom stacksFull-featured web APIs

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

The Node.js Web Module (http and https) is a powerful low-level API for creating web servers. While frameworks like Express simplify things, understanding the core http module gives you full control and insight into how requests are handled.

๐Ÿ” Key Takeaways:

  • Use http.createServer() for building web servers
  • Handle GET/POST routes using req.method and req.url
  • Use https for secure communication
  • Serve HTML, handle form data, and respond dynamically

โš™๏ธ Real-world relevance:
Used in custom microservices, static file servers, CLI tools, and when building your own lightweight backend stack.


โ“FAQs โ€“ Node.js Web Module (http, https)


โ“ What port should I use for HTTP and HTTPS?
โœ… Use port 80 for HTTP and 443 for HTTPS (default web ports). You can use custom ports for development like 3000 or 8080.


โ“ Can I serve JSON using http module?
โœ… Yes. Just set Content-Type to application/json:

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ name: "Node.js" }));

โ“ How do I redirect a user in http?
โœ… Use status code 302 or 301:

res.writeHead(302, { Location: '/new-url' });
res.end();

โ“ Is it necessary to use Express for web apps?
โœ… No. You can build complete applications using only http, but Express simplifies routing, middleware, and error handling.


โ“ How to stop a running server in Node.js?
โœ… You can call:

server.close();

Or press CTRL + C in the terminal.


Share Now :

Leave a Reply

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

Share

๐ŸŒ Node.js โ€“ Web Module

Or Copy Link

CONTENTS
Scroll to Top