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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With