Java Script modules initializing function handler

Going through the's get-started, and I come across a module requirement I can't find clear an explanation of:

var app = require('express')();
var http = require('http').Server(app);

the author describes these lines:

Express initializes app to be a function handler that you can supply to an HTTP server (as seen in line 2)

I haven't found explanations for this usage in any of the documentations for require that I have read. So, what is happening here? is irrelevant to my question. It's only referenced to provide a bit of context. Not sure if this is a simple or complex question...

1 answer

  • answered 2018-03-20 21:17 Francisco Mateo

    When you require('express'), you are importing something. That something is whatever the Express framework chooses to export. If you look at index.js here, we have the following:

    module.exports = require('./lib/express');

    Which you can see it just imports from a sub directory of the project. But you can see it specifically imports express.js. By default (shown here), it exports a function called createApplication:

    exports = module.exports = createApplication;
     * Create an express application.
     * @return {Function}
     * @api public
    function createApplication() {
        // ...

    So when you require('express') it will resolve to function createApplication() which is just a function. Which is why you have the extra (), it's just executing/calling the returned function.

    See Higher-order function.