Reading the request
Method, path, headers and body, turned into a standard Request. The server still answers everything with the same text.
The server from chapter 1 ignores what it is asked. This chapter reads method, path, headers and body, and turns them into a Request object, the same one fetch uses. Every chapter after this works with Request and Response only.
From IncomingMessage to Request
import type { IncomingMessage } from 'node:http';
import { Readable } from 'node:stream';
export function toRequest(msg: IncomingMessage): Request {
const url = `http://${msg.headers.host}${msg.url}`;
const body = ['GET', 'HEAD'].includes(msg.method!) ? null : (Readable.toWeb(msg) as ReadableStream);
return new Request(url, { method: msg.method, headers: msg.headers as HeadersInit, body, duplex: 'half' });
}duplex: 'half' is required by Node when a request has a streamed body. Leave it out and it throws, with a message that names the option.
Still the same answer
$ curl -s localhost:8080/anything
Hello
$ curl -s -X POST localhost:8080/else -d x=1
HelloSame text for every path. Chapter 3 changes that.
subscribe
New entries and the next chapter by mail, nothing else.