AceDevHub
Beginner Node.js Interview QuestionsBeginnerConcept

Node.js · Question 28

What are the req and res objects in Node.js HTTP?

Direct answer

req (IncomingMessage) is a readable stream of the request — method, url, headers, body; res (ServerResponse) is writable — set status/headers, write chunks, end response; both inherit stream backpressure behavior.

Treat req as input and res as output for one HTTP exchange. Large POST bodies should be consumed as streams, not buffered unbounded in memory.

reqres
methodstatusCode (default 200)
urlsetHeader / writeHead
headerswrite / end
Readable stream bodyWritable stream body
socketheadersSent flag
  • Read body — collect chunks: req.on('data'); or use framework parser for JSON.
  • headersSent — after writeHead/send, cannot change status — guard double responses.
  • Framework mapping — Fastify request/reply wrap same concepts with validation and serializers.
req-res-body.mjs
function readJsonBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on("data", (chunk) => chunks.push(chunk));
    req.on("end", () => {
      try {
        resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
      } catch (err) {
        reject(err);
      }
    });
    req.on("error", reject);
  });
}

// In handler:
// const body = await readJsonBody(req);
// res.writeHead(201, { "Content-Type": "application/json" });
// res.end(JSON.stringify({ id: 1 }));