Search code examples
javascriptnode.jseventsbackendfunction-parameter

Where does "request" and "response" come from, and how could I have found out?


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!


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.