Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 299
ferhtgoldaraz Avatar asked Oct 21 '22 19:10

ferhtgoldaraz


2 Answers

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.

like image 170
matth Avatar answered Oct 23 '22 16:10

matth


this should be the create stack: https://github.com/joyent/node/blob/master/lib/http.js#L62 > https://github.com/joyent/node/blob/master/lib/_http_server.js#L253 so if a request is fired, this should be get triggered: https://github.com/joyent/node/blob/master/lib/_http_server.js#L502 - or maybe this: https://github.com/joyent/node/blob/master/lib/_http_server.js#L505

like image 44
floww Avatar answered Oct 23 '22 16:10

floww