0

I'm still somewhat confused by how node callbacks work. Looking at this tutorial: http://www.nodebeginner.org/

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 understanding is that the request and response parameters are passed when the server receives a request. However, I'm not sure how you would tell by the syntax. Does the createServer function not return anything until it actually receives a request, upon which it returns two objects, the request and the response?

2
  • Do you understand how callbacks work outside of Node? Commented May 6, 2014 at 6:25
  • Perhaps I do not. My understanding is that a callback function is just a function passed as an argument. Then, that function can be called at some point. What I'm most unclear about in this case is what is creating the request and response objects. Commented May 13, 2014 at 5:02

1 Answer 1

1

No, the createServer method returns immediately, with a new web server object. That web server object's listen method is then immediately called, and the server begins listening for connections on port 8888. The listen call returns immediately as well; you can demonstrate this by adding a console.log('here'); on the next line and seeing how it writes to the terminal as soon as you run the script. As a result of the listen call, any time a new HTTP request is made to port 8888, the callback which was the sole argument to createServer is called to handle the request.

Since Node runs in a single thread (more or less), any operation that would block that thread--like waiting around for a server connection, or a database query, or a response to a remote request--is handled asynchronously, through the use of callbacks like the one in your example.

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

2 Comments

Thanks Scott. So the request event is an event generated by the web server object? So somewhere in the createServer code there is a definition of when to use the callback? I had previously seen callbacks as something called when a function returns, but in this case it is passed as an argument to an object and is called when an event fires.
Yes, perhaps the term "callback" gets thrown around a bit too much in Node. In this case the argument could be more properly called a "listener", as it is attached to the request event.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.