Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understanding node createServer callback

Tags:

node.js

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?

like image 719
JohnGalt Avatar asked Nov 13 '22 07:11

JohnGalt


1 Answers

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.

like image 95
Nathan Avatar answered Nov 15 '22 06:11

Nathan