1

This is a NodeJS stuff, the code is:

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

My question is how come in the last line, the function onRequest doesn't take parameters.. I'm new to Javascript but isn't onRequest supposed to take 2 parameters as defined in the function? Can anyone help me please? I've been stuck for an hour :(

3
  • 2
    onRequest does take two params, request and response. createServer takes one argument, the event function. Commented Jul 9, 2013 at 1:14
  • Functions are objects. onRequest is a function object. onRequest() calls the function onRequest and returns its value. Commented Jul 9, 2013 at 1:17
  • @john, were any answers helpful? Commented Jul 9, 2013 at 23:11

2 Answers 2

2

You're not actually calling the method. You're telling createServer what its requestListener callback function is.

From the node.js documentation (http://nodejs.org/api/http.html#http_http_createserver_requestlistener):

http.createServer([requestListener])

Returns a new web server object.

The requestListener is a function which is automatically added to the 'request' event.

Sign up to request clarification or add additional context in comments.

Comments

1

Execution of the onRequest function takes 2 parameters.

Your last line:

http.createServer(onRequest).listen(8888);

does not actually execute onRequest, though I can see why you would think it does. It passes a reference to the onRequest function to the http.createServer function / method.

createServer will save a pointer to your onRequest function and then when a request comes into the server, it will execute onRequest. That execution will include a request and response argument.

For details, this article gives a fairly straightforward and concise explanation of this pattern, known as callbacks. It typically goes with asynchronous programming, but doesn't have to.

http://recurial.com/programming/understanding-callback-functions-in-javascript/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.