Kevin Kevin - 4 months ago 116
Node.js Question

response.writeHead and response.end in NodeJs

var https = require('https');
var fs = require('fs');

var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);



  1. Can anyone explain me why do we call the
    writeHead
    and
    end

    method in createServer method.

  2. What is the main purpose of options object passed in createServer
    method.


Answer

Those calls to writeHead and end are not being done in the createServermethod, 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.

Comments