How are inner functions arguments known?

var http = require("http"), fs = require("fs");

var methods = Object.create(null);

http.createServer(function(request, response) {
  function respond(code, body, type) {
    if (!type) type = "text/plain";
    response.writeHead(code, {"Content-Type": type});
    if (body && body.pipe)
      body.pipe(response);
    else
      response.end(body);
  }
  if (request.method in methods)
    methods[request.method](urlToPath(request.url),
                            respond, request);
  else
    respond(405, "Method " + request.method +
            " not allowed.");
}).listen(8000);

So, I just have trouble understanding how the computer knows the values of the “code”, “body” and “type” arguments… I understand they must have been defined during the creation of the “createServer” function but if someone could expound upon this to help me understand better it would be greatly appreciated.

False.

They were defined during the creation of the respond function:
function respond(code, body, type) {
And they were filled when that function is invoked:

Hi @evanr1234 , you’re explicitly passing those arguments here:

    respond(405, "Method " + request.method +
            " not allowed.");

Inside the function, that gives you the following values for the function parameters:

function respond(code, body, type) {
  // code === 405
  // body === 'Method ' + request.method + ' not allowed'
  // type === undefined
}

As for passing that function to methods[request.method], that part will never get executed as methods is an empty object even without prototype.

(x-post)

1 Like

I understand. Thank you.

As a separate but similar question, how dose the computer know what the request and response objects/arguments are? It would be helpful to see how the createServer function was defined but I wasn’t able to find it.

Both are regular arguments getting passed to the callback function you passed to createServer() (namely an IncomingMessage and a ServerResponse object). If you’re not familiar with the concept of callbacks, it works like this:

function doSomething (callback) {
  callback(null, 42)
}

doSomething(function (error, value) {
  console.log('Callback got called with', error, value)
  // -> Callback got called with null 42
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.