tezvyn:

Reading a POST body from the request stream

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

that req is a readable stream.

OUTLINE

body arrives in chunks via data events, accumulate them, on the end event concatenate and JSON.parse inside try/catch.

RED FLAG

expecting req.body to exist or parsing before all chunks arrive.

WHAT THIS TESTS This checks whether you understand that an incoming HTTP request is a readable stream delivered incrementally over the network, not a complete object available synchronously. It reveals whether you know what body-parsing middleware actually does.

A GOOD ANSWER COVERS The request object is an instance of a readable stream. The body has not necessarily arrived when your handler first runs; it streams in over the wire as a sequence of Buffer chunks. You listen for the data event, which fires once per chunk, and accumulate the chunks, typically by pushing them into an array. When the stream emits the end event, the full body has arrived, so you concatenate the chunks into a single Buffer or string and call JSON.parse on it. You wrap the parse in a try/catch because clients can send malformed JSON, and you should respond with a 400 if parsing fails. You may also guard against excessively large bodies to avoid memory abuse.

COMMON WRONG ANSWERS Expecting req.body to be populated, which only exists after Express body-parser middleware runs. Calling JSON.parse inside the data handler before all chunks arrive, which fails on multi-chunk bodies. Forgetting the try/catch, so malformed input crashes the handler.

LIKELY FOLLOW-UPS How would you cap the body size to prevent denial of service. How does express.json do this under the hood. What error event should you also handle on the request stream.

ONE CONCRETE EXAMPLE You write let chunks = []; req.on('data', c => chunks.push(c)); req.on('end', () => { try { const body = JSON.parse(Buffer.concat(chunks).toString()); /* use body */ } catch (e) { res.statusCode = 400; res.end('Invalid JSON'); } });. Only when end fires do you have the whole payload to parse safely.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.