Using the Node.js hello world example:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
I'm trying to find where createServer within http.js "looks for" a function and then passes it two objects (which above are named 'req' and 'res'. I've searched through http.js and the only thing I found was:
exports.createServer = function(requestListener) {
return new Server(requestListener);
};
Does that mean the anonymous function:
function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}
...is passed as 'requestListener' and...
return new Server(requestListener);
...is where the req and res objects get passed back?
Yes. In Javascript functions themselves are "values" you can assign to "objects". Since you can pass an object to another function, then you may pass a function itself as an object.
requestListener
is the parameter createServer
named as requestListener
that is being used to call the Server
constructor
with it.
You can also see this in ruby, where you can call a function and at the same time pass it the code to be executed in a do block, as a parameter.
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