alextc
alextc

Reputation: 3525

Express JS - Run a middleware only the app starts up for the first time

I have an Express JS application built from the Express Generator.

I need to run a middleware to load some constant data from the backend database only the app starst up.

My assumption is that adding the middleware to app.use in the app.js will not be a good idea as it runs every req and res circle and this will deteriorate the performance.

How can it be achieved?

Upvotes: 2

Views: 1099

Answers (1)

Evert
Evert

Reputation: 99841

The way I would approach this, is probably creating a new file with a single function that returns this data + a variable that keeps a cached version around.

For example:

// MyThing.js
let cachedData;

const loadData = () => {

 // Load data for the first time

};

const getData = () => {

  if (!cachedData) loadData();

};

module.exports = {
  getData,
  loadData
};

Now if you ever need to retrieve this data anywhere else, you could do something like:

// Some-other-file.js
const { getData } = require('./MyThing.js'):

console.log(getData());

A few things to keep in mind:

  • My naming is very poor because I don't know exactly what you want to load in.
  • If loading this data is based on an asynchronous operation, such as a network call or database query, make sure these are all async functions.

Upvotes: 1

Related Questions