1

I'm pretty new to javascript - the event-driven language; I'm trying to learn Node.js but the callback function confused me. So I read some tutorial and then I think I get it until I ask myself the following question. Here is a very straightforward code snippet I want to use to illustrate my question.

var http = require("http");

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

My question is: createServer receives a parameter, and this parameter is a callback function definition. The callback function also needs two parameters (response and request) and then the response is going to write something. But who passes the value to response in the callback function? IS this passed by createServer by default in node.js? Can I change the order of request and response? Please correct me if my understanding is wrong.

Thank you for your time.

2 Answers 2

3

But who passes the value to response in the callback function?

If you're asking who supplies the response parameter to your function, the answer (in plainest terms) is Node.js.

If you care to understand it at a deeper code level, you can examine the source. He's the definition for http.createServer():

exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

As can be seen, the requestListener argument is the callback you're referring to. This is used to instantiated a new Server instance.

The Server constructor is defined in the same file, and as can be seen, that requestListener gets registered as an event listener for the 'request' event:

if (requestListener) {
    this.addListener('request', requestListener);
}

From there the code requires a deeper dive to understand everything that happens when a new request comes in, but at a minimum, we can see that the server eventually emits the request event with the req and res parameters:

self.emit('request', req, res);

And since your createServer() callback has been registered as an event listener for request events, it receives those parameters.

IS this passed by createServer by default in node.js?

As explained above, yes - this is default behavior.

Can I change the order of request and response?

Hopefully this is obvious from all the above, but for the sake of completeness, "no".


Edit: to address some of your general confusion on callbacks, maybe this will help...

First of all, whether we're talking about "callbacks", "event listeners", or any other common convention in evented programming, it's important to understand that at the end of the day, they're all just functions. The only thing that makes it a "callback" is a certain set of conventions about how and when it gets, well, called.

Side note: In this particular case, it would actually be more accurate to refer to the createServer() argument as an "event listener", since it gets invoked in response to a particular event (requests).

Either way, though, there's nothing magically different about it. Somewhere along the way, someone has to call that function, and the caller is going to supply the arguments that it receives. There's nothing you can do as the definer of that callback/event-listener/whatever to change the order in which those arguments are supplied, which means we simply need to rely on convention and/or documentation.

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

6 Comments

Very helpful, thanks Jeremy. So one more quick question, according to my understanding from ur comments, createserver is listening to some request to come, if there is one request coming in, it will be invoked. May I know the execution order of createserver and callback function(requestListener)?
Well, nothing is listening for requests prior to calling createServer(). In fact, nothing is listening until you actually call .listen(). Once you have called .listen(), though, then the server instance internally handles incoming requests, and then lets you get involved in the process through your listener. So, order wise, 1) .createServer(), 2) .listen(), 3) [an actual request happens], 4) requestListener is notified.
And just to be clear, 3) and 4) repeat indefinitely. That is, every time a new request comes in, requestListener will be invoked again. No need to keep calling .createServer() or .listen() over and over....
Very clear and helpful! To be general, can I conclude that for all callback functions-if parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback method is then invoked?
I would probably need you to define what you mean by "parent method" there to answer correctly. However, generally speaking, callbacks are used as a way of regaining control after some sort of an asynchronous operation. So basically, you pass your callback to some code that is going to in turn do something asynchronous, and that code agrees to invoke your callback once it's done, so you do whatever you wanted to with the result.
|
0

Yes, createServer() will pass the parameters so you cannot reorder them.

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.