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.
They were defined during the creation of the respond function: function respond(code, body, type) {
And they were filled when that function is invoked:
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
})