@lew
To create a re-usable caching method while using node-cache in Node.js, you can create a utility module that encapsulates the functionality of caching data and retrieving it using the node-cache module. Here is an example of how you can achieve this:
1
|
npm install node-cache |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const NodeCache = require('node-cache'); const cache = new NodeCache(); module.exports = { get: (key) => { return cache.get(key); }, set: (key, value, ttl) => { cache.set(key, value, ttl); }, del: (key) => { cache.del(key); } }; |
In this module, we have created three functions - get
, set
, and del
to interact with the cache. The get
function retrieves the value stored in the cache with the given key, set
function sets a new value in the cache with the given key and time-to-live (ttl), and del
function deletes the value stored in the cache with the given key.
1 2 3 4 5 6 7 8 9 10 11 |
const cache = require('./cache'); // Set a value in the cache with the key 'myKey' and TTL of 60 seconds cache.set('myKey', 'myValue', 60); // Retrieve the value stored in the cache with the key 'myKey' const cachedValue = cache.get('myKey'); console.log(cachedValue); // Delete the value stored in the cache with the key 'myKey' cache.del('myKey'); |
By following these steps, you can easily create a re-usable caching method using node-cache in Node.js. This will help you to efficiently cache data in your application and improve its performance.