Reputation: 3525
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
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:
async
functions.Upvotes: 1