I’m trying to build a command line app using Node.js
I use node-cache for caching some data that comes from API calls.
However when I try to retrieve the data
myCache.get( "key" ) that have been previously set using
myCache.set( "key", data, 10000 ); it is always returning
I guess the issue is when I run the app from the command line I’m creating the cache object every time
const myCache = new NodeCache();.
But without creating the object, caching won’t work obviously. Is there any work around for this?
The cache library you are using is keeping the data in the application memory. So once the app exits, the cache is lost.
In the web application the situation is different because the app never exits (unless it crashes), so the cache stays with the data.
One way to solve this is to store the cache in the external storage like
Redis (but you’ll have to have the Redis server running for that) or maybe just in the text file or SQLite db. You need either to write a simple caching library for that or search for a library that provides the persistent storage.
Update: quick search gives this library: https://www.npmjs.com/package/cache-manager, I didn’t use it, but the docs say it supports may different storages to persist the data and
node-cache-manager-fs might be good for your case.