MyInternships.in

Core Modules

Node.js http Module

The http module creates HTTP servers and clients without any framework. Express and every other Node web framework is built on top of it.


What is http Module in Node.js?

The http module creates HTTP servers and clients without any framework. Express and every other Node web framework is built on top of it.

http Module example

Routing by hand
JavaScript
import { createServer } from 'node:http';

const server = createServer(async (req, res) => {
  if (req.url === '/api/jobs' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify([{ id: 1, title: 'Frontend Intern' }]));
  }

  if (req.url === '/api/jobs' && req.method === 'POST') {
    let body = '';
    for await (const chunk of req) body += chunk;
    const job = JSON.parse(body);
    res.writeHead(201, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ id: 2, ...job }));
  }

  res.writeHead(404).end('Not found');
});

server.listen(3000);

How this works

The request object is a readable stream, so a POST body must be collected chunk by chunk. This is exactly the boilerplate Express removes with one line of middleware.

Key points to remember

  • req is a readable stream; res is a writable stream.
  • Headers must be written before any body content.
  • Writing this by hand once makes it obvious what a framework provides.

Common mistakes with http Module

  • Calling res.end twice, which throws ERR_STREAM_WRITE_AFTER_END.
  • Forgetting the Content-Type header, so clients guess the format.
  • Assuming req.body exists — nothing parses it for you here.

Node.js http Module— Interview Questions & FAQs

Do I need Express, or is the http module enough?+

The http module is enough for a tiny service. Express adds routing, middleware, body parsing and error handling that you would otherwise write yourself, which is why almost every real project uses it.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships