Serialize a Raw HTTP Response
Medium · HTTP
When you call res.end(body), Node writes raw text to the socket. Write serializeResponse(status, headers, body) that builds that text:
1. Status line: HTTP/1.1 <status> <reason> using the REASONS table in the starter (use Unknown for codes not in it).
2. One Name: value line per entry of headers, in the given order. Drop any Content-Length you were given (in any casing), because you compute it yourself.
3. Content-Length: <n> where n is the body size in UTF-8 BYTES, not characters: "é" is 2 bytes and "👋" is 4. new TextEncoder().encode(text).length gives the byte count.
4. An empty line, then the body.
Every line ends with \r\n. A 204 No Content response has no body: skip Content-Length and the body entirely.
(Simplified: real Node also adds headers such as Date and Connection.)