Kevin Kevin - 9 months ago 181
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.end("hello world\n");

  1. Can anyone explain me why do we call the

    method in createServer method.

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


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.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.