Sharing server object in expressJS with another file through module.exports

As I work on my expressJS app, I encountered a situation where I needed to share the server object with another file. To achieve this, I decided to create the server in my app.js file and then expose it to one of my routes.

var server = http.createServer(app).listen(4021, function () {

    var port = server.address().port;

    console.log('http://localhost:%d', port);
});

module.exports = server;

Within the app.js file, I confirmed that the variable holds an object containing relevant server data. However, when attempting to access this variable from my routes.js file using require, I found that it was empty.

var server = require('../../server');

I am puzzled by this issue and would appreciate any insights into what might be going wrong.

Answer №1

Dealing with circular dependencies, such as the one you've described, can present challenges when it comes to implementation and debugging. While this may not directly address your query, if obtaining the port number is your main objective within the route, consider opting for a more straightforward solution. For instance, using middleware that appends the port number to the request object for easy access:

app.use(function(req, res, next) {
  req.port = 4021;
  next();
});

For additional insights, you might find this related SO discussion helpful: Expose vs Creating object in Router file of Nodejs. Although similar, adapting it to fit your scenario proved challenging.

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

The file is not deleted by executing fs.unlink command

When a user uploads a file to my Express server, I want to rename it to match their username. If the same user uploads a new file, the previous one should be replaced. Here is the code snippet: var newPath = 'uploads/' + user.username + &apos ...

Swap out the svg element with an icon alternative

Transforming Circle Elements into Shopping Cart Icons I am attempting to change the appearance of my SVG circle elements to resemble shopping carts. Is there a method to completely alter the definition of a circle element in svg so that it displays a spec ...

mastering the chrome api within your redux-saga workflow

Currently, I'm working on creating a 'get_current_url' function using redux-saga in my project involving a Chrome extension built with React.js. In order to obtain the current URI, I need to utilize the chrome.tabs.query API. Below is the sn ...

Combining multiple data types in an AJV array

Imagine you have the following defined type: type MixedArray = Array<number | string>; Now, let's say you have some sample data that needs to be validated: [ 'dfdf', 9, 0, 'sdfdsf' ] How can you create an Ajv JSONSchemeType ...

Using Node and Express to Serve Multiple Rendered Views in a Single Response

I'm making an AJAX request and I want to receive a JSON response containing multiple partial views that I can use to update different sections of my page. For example: { "searchResults": "<div>Some HTML string</div>", "paginationB ...

Guide to iterating through a queue of promises (sequentially handling asynchronous messages)

Currently, I am working on processing a queue of promises (which are representations of messages) in a specific order and using AngularJS for the task. Just to give you an idea, let's say that I have a method called connect() which returns a promise ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Error in MongoDB Connection: Timeout issue caused by an unresolved Promise

Issue Overview Whenever I attempt to execute nodemon server, a timeout error is displayed indicating [nodemon] app crashed - waiting for file changes before starting.... Detailed Problem Description I have three files located at the following paths: ...

JavaScript for creating dropdown menus using Twitter Bootstrap

I've been struggling to get the dropdown menus in my Twitter Bootstrap project to function properly. Below is the code I have for the navbar: <div class="container-fluid"> <div class="row-fluid"> <div class="span12"> < ...

Can you explain how to use a toggle switch to make a select dropdown select a random option?

Currently, I am in the process of setting up a page for a character generator. Users will have the option to randomize traits or input their own. The interface includes toggle switches for the "choice vs random" options for each trait category, as well as ...

In React JS, the material-ui Accordion component's onchange function is failing to retrieve the current value

I am encountering an issue with the @material-ui Accordion where the onChange function is not capturing the current value. For example, when I click on the panel1 icon, it opens panel2 instead of taking the current value on icon click. I have provided the ...

What could be the reason for my code showing "success" instead of the intended outcome?

I'm currently working on a project that focuses on verifying whether ingredients are halal or haram. MongoDB is being used to store ingredient information, and express is managing the requests. After sending a GET request to /ingredients/{ingredientn ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Ways to prevent a timeout when the score exceeds 1000

Could someone help me with clearing the interval and resetting the score in my code? It seems to be working fine, but when the score goes over 1000 and I hit reset, it doesn’t reset completely. I've tried placing the clearTimeout functions before e ...

Error: Attempt to use a non-function object. Issue encountered while attempting to make a POST request using the Mern stack with fetch

I encountered an issue while working on a MERN stack project where I am trying to send a post request to create a new user in MongoDB. The error message states that "TypeError: Object(...) is not a function". This problem has left me puzzled as I have only ...

Using node-mongodb-connection to establish a connection with connect-mongo

When it comes to connecting to my database, I typically do it in the following way: var mongoClient = new MongoClient(new Server('localhost', 27017, {auto_reconnect: true})); mongoClient.open(function (err, mongoClient) { var db = mongoClient. ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

Having two identical select2 forms on the same page

Integrating two select2 multi-value select boxes into my Rails application is proving to be a challenge. While the top form functions correctly, the bottom one refuses to work as expected. Despite my attempts at changing IDs and adding new JavaScript cod ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

What is the best way to retrieve a PDF file from another website and showcase it on our own site without any redirection?

Is there a way to display a pdf from another website without having to redirect to that site? I'm looking for a solution that involves using the URL directly. ...