In-memory Cache for Node.js

5.1.2 · active · verified Sun Apr 19

node-cache is a simple, fast, and internal in-memory caching module for Node.js applications, designed to function similarly to memcached but within a single Node.js process. It supports setting key-value pairs with optional time-to-live (TTL) expiration, allowing for automatic invalidation and deletion of stale data. The current stable version is 5.1.2, actively maintained with regular updates addressing bug fixes and minor features, as evidenced by recent 5.x releases. A major breaking change in v5.0.0 removed callback support, shifting entirely to synchronous operations (with an opt-in legacy callback option for migration), and dropped the `lodash` dependency, improving performance and reducing the bundle size. It differentiates itself by its straightforward API and focus on local process caching, suitable for scenarios where a full-fledged external caching solution like Redis or Memcached is overkill. Keys can be strings or numbers, and the cache can be configured with standard TTLs, periodic cleanup, and an option to store references vs. clones of values, balancing performance and data isolation.

Common errors

Warnings

Install

Imports

Quickstart

Initializes NodeCache, sets and retrieves a value with a TTL, demonstrates handling missing keys, simulates caching an asynchronous operation, and shows the `take` method for atomic get-and-delete.

import NodeCache from 'node-cache';

const myCache = new NodeCache({ stdTTL: 60, checkperiod: 120, useClones: false });

myCache.set('myKey', 'myValue', 10); // Cache for 10 seconds

let value = myCache.get('myKey');
if (value) {
  console.log(`Retrieved: ${value}`);
} else {
  console.log('Key not found or expired.');
}

// Simulate an async operation and cache its result
async function fetchDataAndCache(key) {
  let cachedData = myCache.get(key);
  if (cachedData) {
    return cachedData;
  }
  console.log('Fetching fresh data...');
  const freshData = await new Promise(resolve => setTimeout(() => resolve({ id: 1, name: 'Fresh Data' }), 500));
  myCache.set(key, freshData, 30);
  return freshData;
}

fetchDataAndCache('asyncData').then(data => console.log('Async data:', data));

// Get and delete a key with a single operation (v5.1.0+)
const takenValue = myCache.take('myKey');
console.log(`Taken value: ${takenValue}`);
console.log(`Is myKey still in cache? ${myCache.has('myKey')}`);

view raw JSON →