Implementing single execution of asynchronous functions in express

Can anyone provide guidance on how to ensure asynchronous functions are only executed once within an Express application? I'd like to avoid running this function on every route and am seeking a more express-friendly approach.

var packageJson = false
app.use(function(req, res, next){
  if(req.packageJson) return next()
  if(packageJson){
    req.packageJson = packageJson
    return next()
  }
  return fs.readFileAsync("./package.json", "utf8")
  .then(JSON.parse)
  .then(function(data){
    packageJson = data
    req.packageJson = data
    return next()
  })  
})

Answer №1

I suggest refraining from running the asynchronous function within the initial call to that route. Instead, consider implementing the following code:

var jsonData = fs.readFileAsync("./data.json", "utf8").then(JSON.parse);
app.use(function(req, res, next){
  if (req.data)
    return next();
  else
    jsonData.then(function(data){
      req.data = data;
      return next();
    });
});

It is crucial to handle errors appropriately. If the promise for jsonData is rejected, your route may potentially hang indefinitely.

Answer №2

For those looking for a specific solution (not a general one like @Bergi's), in this scenario you have the option of utilizing require(). This method provides two key advantages:

  • It is capable of directly loading JSON files
  • It stores file data in memory for efficient access

To implement this middleware, you can use the following code snippet:

app.use(function(req, res, next){
  req.packageJson = require('./package.json');
  return next();
});

Although the initial request may experience a slight performance hit due to the synchronous nature of require(), subsequent requests will benefit from automatic retrieval of data stored in memory.

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

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

Troubleshooting Problem with Parsing Float in Angular

Currently, I am facing an issue while using a filter to calculate totals from dynamic data in ng-repeat. The problem lies in my inability to limit the decimals to 2 places. Below is the code snippet of my filter: app.filter('sumByKey', function( ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

Managing multiple POST requests from different routes simultaneously

My website features a basic contact form located in the footer section (in footer.pug): form(method="POST" action="contact_form") input(type='email' name='ct_email' data-name='ct_email' required) textarea(type='text& ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

By utilizing Node and Express for handling requests to get(/foo/:bar) routes, a situation may arise where all relative links in the template become relative to /foo instead of the root directory (/

In my node server code, the problematic route is: app.get('/s/:searchTerm', function(req, res) { res.render('index'); }); This causes all relative links in index.jade to be related to "hostname/s/" instead of just "hostname/", which ...

Find the quantity of items in each list individually and add them to a new list

Seeking a solution for a seemingly simple issue. I am attempting to calculate the number of list items and then add this count to the list in the parent div. The problem lies in the fact that it always displays the value of the last item in the list. For i ...

What is the best way to bring HTML files into the dist directory?

When working in my development environment, I utilize the following code: res.sendFile(path.resolve(__dirname,'../Views/setpwd.html'); It functions correctly within the development environment. However, when moving to production, the Views are ...

When attempting to display the details of each restaurant on my detail page, I encountered the error "Cannot read property 'name_restaurant' of undefined."

I have set up dynamic routing for a ProductDetail page, where each restaurant has its own details that should be displayed. The routing is functional, but I am facing difficulty in retrieving data from Firestore using the restaurant's ID. PS: Althoug ...

The confusion arises from the ambiguity between the name of the module and the name of

In my current scenario, I am faced with the following issue : module SomeName { class SomeName { } var namespace = SomeName; } The problem is that when referencing SomeName, it is pointing to the class instead of the module. I have a requireme ...

What makes an Angular project different from conventional JavaScript projects that prevents it from running in a browser like any other?

When attempting to run index.html from the dist folder in the browser, I encountered issues. This is different from an AngularJS application where simply importing the script file into index.html allows the application to work seamlessly. Why is it not po ...

Why does Vue.js Vuex dispatch an action when importing module stores into a helper file?

I recently developed an application using Vue.js. The app is divided into several modules, each corresponding to a specific route and containing a main component with numerous sub-components/children. Every module has its own store, actions, mutations, get ...

Encountering a JSLint error while attempting to import the 'aws-amplify' package in my main file

Recently, I installed the latest version of aws-amplify using npm. After running npm init with 'entryPoint.js' as the entrypoint file, I encountered an issue when pasting the following code at the top of entryPoint.js: import Amplify, {Auth} from ...

Unable to locate xpath during the second iteration or attempt

As a newcomer and hobbyist programmer, I have hit a wall with this particular issue. My goal is to loop through a website and extract data to print. While my code successfully retrieves data from the first link, I am struggling to make it "click" on the se ...

concerning a snippet of programming code

I'm new to coding and I'd like some help understanding this piece of code, particularly the red colored fonts. Which page value are they referring to? $(function() { $("#title").blur(function() { QuestionSuggestions(); }); }); funct ...

Session Redirect Error in Express.js

Encountering an error consistently when running my code with the pseudocode provided below (Just to clarify, my code is built on the react-redux-universal-hot-example) Error: Can't set headers after they are sent. [2] at ServerResponse.OutgoingMe ...

Testing Angular 2: Ensuring Component Properly Calls Router with Accurate Arguments

I'm facing an issue with a child component that includes a button element with 'routerlink' attribute for navigation upon clicking. The button does not have a '(click)' handler, only the routerlink. Currently, I am writing a unit ...

Cross-project AntiForgeryToken validation doesn't work within the same solution's sub-projects

Currently, I am working on implementing CSRF in an MVC application. In order to validate the token for inputs that are JSON encoded and called via Ajax, I have created a custom attribute. The validation works perfectly within the same project. However, whe ...

How can I efficiently make a dropdown menu with search functionality instead of using datalist?

I am currently working on creating a custom searchable input field that makes backend calls. Instead of using datalist, I want to design a unique UI with ul and li items. While I have successfully implemented the search functionality, I am facing a glitc ...

Node.js is encountering an undefined parameter in the function definition

I've encountered an issue while working on an application utilizing MongoDB as the database and node.js. I have a function that is supposed to receive a parameter named orderedBy, but when I console.log it, it appears as undefined. Can someone help me ...