Those calls to writeHead
and end
are not being done in the createServer
method, but rather in a callback.
It's a bit easier to see if you split out the callback into a separate function:
function handleRequest(req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(options, handleRequest).listen(8000);
So here we define a handleRequest
function and then pass that into the createServer
call. Now whenever the node.js server we created receives an incoming request, it will invoke our handleRequest
method.
This pattern is very common in JavaScript and is core to node.js' asynchronous event handling.