Ted
Ted

Reputation: 756

Is it possible to define a global variable across an entire Node Express server?

I'm creating a Node/Express application that is dependent on data that is fetched from an API. The issue is that my application has to fetch quite often from the API and do some intensive calculations every time, so I want to cache results from both the API and the intensive calculations.

I already wrote out some very rudimentary caching functionality (i.e. writing values into a text file), but I'm curious if there's a way to keep the values in memory in some sort of object for easy access across the whole application (e.g. across multiple files) instead of having a util function to read in the values from a text file every time.

For example, maybe I have a paradigm that looks like this:

When the server first initializes, I fetch for the data, and create some sort of cached value:

const data = await api.get('colors');


const map = {
  red: data.red,
  blue: data.blue,
  green: data.green,
}

In one of my controllers, I want to access map and be able to use the values. So maybe I'd be able to do something like this:

import { map } from './utils/mapManager.js'

const getGreenValue = (req, res) => {
   res.send(map.green);
}

What is the best way to design a system that is trying to achieve this behavior?

Thanks in advance, and happy to answer any clarifying questions.

Upvotes: 2

Views: 1115

Answers (3)

Kalesh Kaladharan
Kalesh Kaladharan

Reputation: 1058

I suggest you to try express specific app.locals or res.locals.

Say you have an app initialized like

const app = express();

const data = await api.get('colors');
const map = {
  red: data.red,
  blue: data.blue,
  green: data.green,
}

//Assign it to locals
app.locals.map = map;

Now the map is available throughout the lifetime of application and you can access the same in views just by calling the variable map.

res.locals does the same thing but it is available only until the lifecycle of request. Say, you want to send a particular color based on the request. You can do it like this.

app.use(function(req, res, next){
    if(req.params.id==='admin')
        res.locals.color = req.app.locals.map.red;
    else
        res.locals.color = req.app.locals.map.blue;
     next();
});

With the above middleware, you will be able to have a variable color that is available to all the succeeding middlewares and the final view. You can access the same in view using color. This is persistent till the lifetime of that request.

Upvotes: 0

SuleymanSah
SuleymanSah

Reputation: 17858

You can use expressjs app.locals property.

To write data:

app.locals.map = map;

To read data:

let map = app.locals.map;

Docs:

https://expressjs.com/en/api.html#app.locals

Upvotes: 1

Abhishek Mani
Abhishek Mani

Reputation: 522

Please refer this doc -> Global

You can use global object in this case.

console.log(globalString); // Output: "This can be accessed anywhere!"

globalString = "Check me out now";
console.log(globalString); // Output: "Check me out now"

globalString = undefined;
console.log(globalString); // Output: undefined```



Upvotes: 0

Related Questions