Home > OS >  Use closure to store and access state in different files
Use closure to store and access state in different files

Time:01-17

Is it possible to use closure as inter function dto between two files?

This is my test code, the idea I am trying to work out, and it might as well be false, because I am coming from Java land and the dto way of thinking is doing well in me, is to create closure (store.js) in my app file (index.js), have that closure store some state, and then load this closure in another file (router.js).

If this is wrong is there a better way to do it? My aim is to access Request object by reference from multiple files, rather than possibly passing it around as a function argument.

store.js

store = function(request) {
   let req = request
   function getRequest(){
     return req
   }
   return getRequest
}

module.exports = store;

index.js

var express = require('express');
var app = express();
var router = require('./router');
var store = require('./store')

app.use(function(request, response, next){
   require('./store')(request)
   next()
})

app.use('/', router);
app.listen(3001);

router.js

var express = require('express');
var router = express.Router();

router.get('/:id', function(req, res){
  const store = require('./store');
  res.send('store = '   store());
});

module.exports = router; 

CodePudding user response:

what your code does can be explained like this :

require('./store') "is" a function, which expects a request object. therefore you can effectively call it in your app.use part.

But in router.js you are still calling this very same function which also expects a request object. it acts like : let req = null. since you call it without the request object it will return nothing.

What you want to achieve is a problem not fully solved in nodejs (for real). or at best not stable for every package i needed. for exemple this concept has never worked for me with npm mysql. hence stoping me from using it at all. be stable or be gone :p

Here is a full explaination of how you can efectively create a store like the one you tried to do.

https://www.freecodecamp.org/news/async-local-storage-nodejs/

maybe things has gotten better recently. Please ping me if you manage doing it.

i tried some libs : continuation-local-storage cls-hooked async_hooks

  •  Tags:  
  • Related