Store an object in memory between requests using SailsJS / Express

I create a server using SailsJS (a framework built on top of Express), and I need to keep the object in memory between requests. I would like to do this because loading it to / from the database takes too much time. Any ideas how I could do this?

Here is my code:

var params = req.params.all(); Network.findOne({ id: params.id }, function(err, network) { if(network) { var synapticNetwork = synaptic.Network.fromJSON(network.jsonValue); if(synapticNetwork) { ... 

In particular, the fromJSON() function takes too much time, and I would prefer to keep the synapticNetwork object in memory while the server is running (otherwise load it when the server starts and just saves it periodically).

+6
source share
2 answers

There are many caching libraries, one of which is node-cache , as you already mentioned. They all have a similar api:

 var cache = require('memory-cache'); // now just use the cache cache.put('foo', 'bar'); console.log(cache.get('foo')) 

You can also implement your own module and just require it where you need it:

 var cache = {}; module.exports = { put: function(key, item) { cache[key] = item; }, get: function(key) { return cache[key]; } } 
+12
source

There are many potential solutions. The first and most obvious is the use of session middleware for express delivery. Most web frameworks should have some kind of session solution.

https://github.com/expressjs/session


The next option would be to use a caching utility, for example, what Vsevolod suggested. It does almost the same thing as a session, except that the data must be bound to the user / session, then you will have to store some kind of identifier in the session and use it to retrieve from the cache. I think this is a little redundant if this is your use case.

There are also utilities that will expand your mid-level sessions and store objects in a session in a database or in other types of data stores so that session information is not lost even after a server restart. You still get the storage speed in memory, but maintain the database if memory in memory is flushed.


Another option is to use Redis . You still have to serialize / deserialize your objects, but Redis is a data store in memory and can write and read very quickly.

+1
source

Source: https://habr.com/ru/post/984061/


All Articles