-2

I'm trying to set GLOBAL variable available across all modules of Node.js app.

module.exports = app => {
  app.get('/config', async (req, res) => {
     .....
     const { data } = await axios.get('.....')
     app.locals.MY_CONFIG = data.config

Then in other module:

module.exports = app => {
      app.post('/getData', async (req, res) => {
         .....
         const { data } = await axios.get('.....')
         if (app.locals.MY_CONFIG.prop1 === true) {
             .....
         } else {
             .....
         }

Will this line cause memory leaks every time the route is called?

app.locals.MY_CONFIG = [data.config]

in other words will this cause an issue:

app.locals.MY_CONFIG = [data.config]
app.locals.MY_CONFIG = [data.config]
app.locals.MY_CONFIG = [data.config]
app.locals.MY_CONFIG = [data.config]
...
5
  • 1
    Currently there's no reason to assume a leak. It's unknown how MY_CONFIG is used, this is what affects the possibility of a leak more Commented Jun 27 at 11:59
  • it will be used in other modules where other routes defined. Question updated Commented Jun 27 at 12:00
  • 1
    @JohnGlabb I mean the exact code, not just a place. If there would be code keeps a reference to stale MY_CONFIG value, there would be a leak. In your case if (app.locals.MY_CONFIG.prop1 === true) there's no danger of this so far Commented Jun 27 at 12:04
  • Barring GC bugs, In a garbage-collected language, memory leaks can only happen if you keep a reference to a value in another variable when you reassign the variable you care about. Why would you suspect a memory leak problem from what you've shown? Commented Jun 27 at 13:46
  • it makes me scary to assign and OBJECT especially to global variable Commented Jun 27 at 13:52

1 Answer 1

0

By doing app.locals.MY_CONFIG = [data.config] you're overwriting the previous value of app.locals.MY_CONFIG. Assuming you aren't holding another reference to it somewhere, that old value is now eligable for garbage collection. In other words, there is no memory leak in the snippet provided in the question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.