Initializing function handler for Java Script modules

As I was diving into the socket.io's get-started guide, I stumbled upon a module requirement that left me puzzled:

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

The explanation provided by the author is as follows:

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

I couldn't find any clear explanations for this specific usage in the documentation I checked. So, what exactly is going on here? Although Socket.io is mentioned, my question is unrelated to it and is purely focused on understanding this coding snippet. Not sure if this falls under a simple or complex query...

Answer №1

Importing express means bringing in something that the Express framework decides to make available through export. The code snippet in index.js can be found here:

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

This shows that it imports from a subdirectory within the project, specifically importing express.js. By default (as seen here), it exports a function named createApplication:

exports = module.exports = createApplication;

/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */

function createApplication() {
    // ...
}

When you require('express'), it points to function createApplication(), which is simply a function. This explains why there are parentheses like (); they execute/call the returned function.

Explore more about Higher-order functions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Should we always make it a point to end responses in Express with a status code, or is it just

I'm noticing a pattern in how people respond to requests. Some prefer simply using res.send(); while others opt for including a status code, such as res.status(422).send();. It seems that the latter method is particularly helpful when dealing with dat ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

another solution instead of using several try-catch blocks within a function

Consider a scenario where we define a function as shown below: async function doSomethingWithFriends() { let user, friends, friendsOfFriends = null; try { user = await getUser(); } catch(err){ return [401, err] } try { ...

I'm confused as to why MongoDB is flagging this as an invalid JavaScript object when attempting to run the update method

Encountering an error while attempting to update a record: (node:2018) UnhandledPromiseRejectionWarning: MongoError: document must be a valid JavaScript object Here's the code in question: global.db.collection("groups").find ...

Tips for organizing a data string that does not conclude with a null character

I need to create a dataSet with the following patterns: (11,22) , (11,22,33) , (11,22,33,44) , (11,null,33,44),(11,null,null,44),(11,null,33) However, it must not end with null. (in other words, the dataSet string should not be like (11,22,null,null)). ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Awaiting fulfillment - Promise remains pending as loop executes queries

I have a scenario where I receive an array containing multiple data elements and need to perform a query for each element in the array. However, this is resulting in a promise pending response. How can I resolve this issue? What could be causing it? getFa ...

Sending Twilio SMS Data from Node to React can be achieved by passing the post data

Currently utilizing Twilio for receiving SMS messages on my server, I am seeking a way to display the returned data in React. As Twilio sends data only server-side via a POST request when a text is sent from my phone, how can I access this POST data in m ...

TinyMCE - The control with the name 'content' is considered invalid and cannot receive focus

I am utilizing TinyMCE 4 and here is the code snippet for it: <script type="text/javascript" src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea[name=content]', ...

Issue: Trouble with Rotating Tooltips in Javascript

I am facing a challenge with the tooltips on my website. I want to ensure that all tooltips have a consistent look and transition effects, but I am struggling to achieve this. The rotation and other effects applied using javascript are not functioning prop ...

Upgrade the JavaScript source code from the backbean JSF

In my XHTML file, I have included Javascript like this: <script src="test1.js"></script> Additionally, I have a few other Javascript files which are actually themes. I want to provide users with the option to change the theme (Javascript nam ...

Issue with Karma: encountering error "ocLazyLoad initialization failed"

While attempting to run the tests from the quickstart sb-admin-angular, I encountered an error stating unable to init ocLazyLoad. (This issue is occurring on a Windows 7 machine.) The command I am using to run the tests is: $ grunt test --force After re ...

What is the best way to access all of the "a" elements contained within this specific div?

Chrome websites are built using the following structure: <div class="divClass"> <a class="aClass"></a> <a class="aClass"></a> <a class="aClass"></a> </div> Utili ...

Retrieve DOM elements within a Vue.js modal using JavaScript

I have integrated the Vue.js modal into my Vue app using a Vue component. The template section of this component includes the modal itself: <template> <!-- Modal: Edit exercise --> <modal name='edit-exercise-modal' ...

I am in search of a regular expression to validate a Jordanian phone number, whether it includes the country code or not

Looking for a regex pattern that can validate phone numbers beginning with either 0096279, 0096278, 0096277, or 079, 078, 077. ...

How can one properly utilize material-ui CSS?

Just starting out with material-ui and react, I'm currently following this palette customization guide from Material-UI. However, when attempting to replicate the example shown, I encountered the error: Cannot read property 'prepareStyles' ...

How can we enhance our proxyURL in Kendo UI with request parameters?

As outlined in the Kendo UI API documentation, when using pdf.proxyURL with kendo.ui.Grid, a request will be sent containing the following parameters: contentType: Specifies the MIME type of the file base64: Contains the base-64 encoded file content fil ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

Using React.js to dynamically change a CSS class depending on a certain condition

I am trying to assign a CSS class to a div based on a specific condition. The issue I am facing is that it always takes the last condition. Below is the code snippet: When I run the code, I receive logos.length as 3 <div className= "${ (this.state. ...

gathering identical objects in the collection

I need to calculate the total time of the specified objects and display it in a single list. Here is the object data: var list = [ { 'user': 'Tom', time: 270547 }, { 'user': 'Alex', time: 82081 }, { 'user&apo ...