What is node-cache?
node-cache is a lightweight library for internal data caching in Node.js applications. It works as an in-memory store, allowing you to temporarily save computation results, API responses, or database data to avoid repeating heavy operations.
Why is caching needed in JavaScript?
Caching is critically important for performance. Without it, every server request can lead to repeated calls to external services, database queries, or complex computations. node-cache solves this problem by storing data in memory with a specified time-to-live (TTL). This reduces server load and cuts response time by 2–5 times for frequently requested data.
Installation
To install the library, run the following command in your project root:
npm install node-cacheAfter installation, include the module in your code:
const NodeCache = require('node-cache');Main Functions
- set(key, value, [ttl]) — saves a value by key with an optional time-to-live in seconds.
- get(key) — returns the saved value or undefined if the key is not found or has expired.
- has(key) — checks if a key exists (returns true/false).
- del(key) — deletes one or more keys.
- flushAll() — clears the entire cache.
- keys() — returns an array of all active keys.
- getStats() — statistics: hits, misses, keys, ksize, and vsize.
Node.js Code Example
const NodeCache = require('node-cache');const myCache = new NodeCache({ stdTTL: 600, checkperiod: 120 });
// Save datamyCache.set('user_123', { name: 'Alice', role: 'admin' }, 300);
// Retrieveconst user = myCache.get('user_123');if (user === undefined) { console.log('Cache is empty, fetching from DB');} else { console.log('Data from cache:', user);}
// Statisticsconsole.log(myCache.getStats());// { hits: 1, misses: 0, keys: 1, ksize: 8, vsize: 32 }When to use node-cache?
The library is ideal for:
- Caching API responses — avoid repeated requests to external services (e.g., weather, exchange rates).
- Results of heavy computations — save data processing results for 5–10 minutes.
- Session data — temporary storage of tokens or user settings.
- Intermediate cache between microservices — reduce network calls.
Important: node-cache is not suitable for distributed systems (it works only in the memory of a single process). For distributed caching, use Redis or Memcached.
Conclusion
node-cache is a minimalistic and reliable solution for in-memory caching in Node.js. It requires no configuration of external services, integrates easily, and significantly speeds up your application. Start using it today by adding just a few lines of code.
Also in library
GraphQL in Swift: Complete Guide to the Apollo iOS Library
Task Queues for Rust: Overview of Popular Libraries and Tools
GraphQL Java — server library for implementing GraphQL API in Java