Question

I've decided to learn node, an so I'm following, to begin with, The Node Beginner Book. As in I guess a lot of other resources, there is the "simple HTTP server", first step, something like:

var http = require("http");

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

As I understand it, when someone, in this case me though localhost:8888, makes a request, an event is triggered, and the anonymous function that got passed to http.createServer gets fired. I put here the documentation that I've managed to find about http.createserver for anyone that finds it useful:

http.createServer([requestListener])

Returns a new web server object.

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

(from the node.js site)

I couldn't find or figure out through how does this triggered function get it's parameters passed, and how do I find out about it. So... how do I know where does these parameters come from, what methods do they offer, etc?

Thanks in advance!

Was it helpful?

Solution

In JavaScript, functions can be passed into methods as a parameter. Example:

function funcA(data) {
    console.log(data);
}
function funcB(foo) {
    foo('I'm function B');    // Call 'foo' and pass a parameter into that function
}
funcB(funcA); // Pass funcA as a parameter into funcB

What you're doing with http.createServer is the above, passing a function that can accept parameters. A new server expects you to pass in a function that it can call. The server will do internal actions which it will create a request and response object, and then call the function you passed in with those variables.

Read about the Http Event: Request for details about these parameters.

OTHER TIPS

The node.js documentation, explains pretty much everything you need to know about a http.ClientRequest and a http.ServerResponse, including methods and events.

If you need information about the HTTP protocol in general, you can find a lot of resources by googling it, such as the HTTP Wikipedia page.

If you want to see in details how HTTP is implemented in node, you'll have to jump into the node.js source code.

Also, you might be interested in express.js, which the most used web framework for node, hence a lot of resources about it are available online.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top