I think there is a subtle difference, but one which doesn't make much (any?) difference in this case.
With Node.js
's require
statement what you end up with is the object that the module assigns to module.exports
. This could be anything, even just a simple value, but it could also be a function.
Thus, suppose you have the following module in myModule.js
:
function complexOperation() {
// blah blah
}
module.exports = complexOperation;
When you do:
var myModule = require("myModule.js");
You end up with myModule
set to complexOperation
, and you would call it just like any regular function. Straightforward. But note that it wouldn't necessarily make sense to do something like new complexOperation()
here - all depends on what complexOperation
is.
In the case of Express.js
the object returned is itself a function, namely, createApplication
(defined in this file: https://github.com/strongloop/express/blob/master/lib/express.js). So require('express')
returns a function, which is assigned to express
, and which is then run on the next line. So app
ends up with the result of the execution of the function createApplication
.
The second variation (ignoring the fact that, as one comment-er pointed out, you misquoted that source file) uses the new
keyword. When you do:
var a = new Something();
Something
should be a function - a constructor function. And what this statement does is:
- create a new object
- invokes
Something()
with this
set to the new object
- returns the result of
Something()
(There is more going on, with the object's prototypes being setup. Full explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new).
So in the above case, the statement var app = new Express()
creates a new object, invokes Express()
with this
set up to refer to the newly created object, and then returns the result.
In the case of Express.js
, because the thing exported is itself a function, much the same result is achieved. A new object is created, createApplication
is run with this
setup accordingly, and then app
gets the result of createApplication
.