0

Going through the socket.io'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? Socket.io 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...

  • You're asking how `require()` works? Have you read this question: [**What is this Javascript “require”**](https://stackoverflow.com/questions/9901082/what-is-this-javascript-require)? – Obsidian Age Mar 20 '18 at 20:48
  • What is the difference between require('some_module')(); and require('some_module'); ? – CuriousGeorgre Mar 20 '18 at 21:02

1 Answers1

0

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.

Cisco
  • 20,972
  • 5
  • 38
  • 60