A little help with some Nodejs/Express code

A little help with some Nodejs/Express code
0

#1

Hello,

I m trying to learn Node Js and Express and I encountered a code like this :

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

I m can t really understand the logic behind this code, I mean I m getting confused when i see that listen is a method of app which makes app an object I guess. Now it comes the confusing part when this method it s literally returning itself as a method of server declared inside: return server.listen.apply(server, arguments);
Is it someone patient to explain what happens in this code ? I m a little confused about this self returning and as I see as a method of server this time.


#2
  1. Define a method called listen on the object representing the application (app)
  2. In that (and in the context of that,which is why you pass this), intialise an object representing the server using the constructor Node provides (http.createServer).
  3. Then the method returns the result of the server’s own listen method.

It’s basically grabbing all of the functionality of Node’s server listen and attaching onto the (Express) app’s listen. It means that, when you manually create the server this way, you can attach other bits of functionality, e.g. you can do things like easily provide HTTP and HTTPS versions.

Note you don’t need to actually ever write the code you posted, you just use app.listen() or {http|https}.createServer(app).listen(), that’s what that method you posted gives you


#3

Ah so it is not returning itself; it s not the same listen that we create on app it just grabs the other listen from http object. Ty for your help I appreciate it :slight_smile: