{"id":11413,"library":"node-cache","title":"In-memory Cache for Node.js","description":"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.","status":"active","version":"5.1.2","language":"javascript","source_language":"en","source_url":"git://github.com/node-cache/node-cache","tags":["javascript","cache","caching","local","variable","multi","memory","internal","node","typescript"],"install":[{"cmd":"npm install node-cache","lang":"bash","label":"npm"},{"cmd":"yarn add node-cache","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-cache","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While CommonJS `require` is shown in examples, modern Node.js development typically uses ES Module `import`. The package still exports a default CommonJS module.","wrong":"const NodeCache = require('node-cache');","symbol":"NodeCache","correct":"import NodeCache from 'node-cache';"},{"note":"The primary export is a default CommonJS export, so `require` syntax directly assigns the class. For ESM, a default import is used.","wrong":"import { NodeCache } from 'node-cache';","symbol":"NodeCache","correct":"const NodeCache = require('node-cache');"},{"note":"Events emitted by the cache (e.g., 'expired', 'set', 'del') are exposed as constants for better type safety and discoverability.","symbol":"NodeCacheEvents","correct":"import { NodeCacheEvents } from 'node-cache';\n// Usage: myCache.on(NodeCacheEvents.EXPIRED, ...)"}],"quickstart":{"code":"import NodeCache from 'node-cache';\n\nconst myCache = new NodeCache({ stdTTL: 60, checkperiod: 120, useClones: false });\n\nmyCache.set('myKey', 'myValue', 10); // Cache for 10 seconds\n\nlet value = myCache.get('myKey');\nif (value) {\n  console.log(`Retrieved: ${value}`);\n} else {\n  console.log('Key not found or expired.');\n}\n\n// Simulate an async operation and cache its result\nasync function fetchDataAndCache(key) {\n  let cachedData = myCache.get(key);\n  if (cachedData) {\n    return cachedData;\n  }\n  console.log('Fetching fresh data...');\n  const freshData = await new Promise(resolve => setTimeout(() => resolve({ id: 1, name: 'Fresh Data' }), 500));\n  myCache.set(key, freshData, 30);\n  return freshData;\n}\n\nfetchDataAndCache('asyncData').then(data => console.log('Async data:', data));\n\n// Get and delete a key with a single operation (v5.1.0+)\nconst takenValue = myCache.take('myKey');\nconsole.log(`Taken value: ${takenValue}`);\nconsole.log(`Is myKey still in cache? ${myCache.has('myKey')}`);","lang":"typescript","description":"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."},"warnings":[{"fix":"Rewrite code to use synchronous methods (e.g., `cache.get(key)` instead of `cache.get(key, callback)`). For a temporary migration path, initialize with `new NodeCache({ enableLegacyCallbacks: true })` but note this will be removed in v6.x.","message":"Version 5.0.0 completely removed support for callback-based API methods. All operations are now synchronous. If you rely on callbacks, you must migrate to synchronous calls or temporarily enable legacy callbacks.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Upgrade your Node.js runtime to version 8.0.0 or higher. The recommended version is the latest LTS.","message":"Node.js versions prior to 8.x are no longer supported since v5.x. Running on older Node.js environments will lead to compatibility issues or errors.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Review code that explicitly sets TTL to 0 or relies on `stdTTL=0` to ensure it's intended for unlimited expiration, not immediate deletion. For immediate deletion, use `.del(key)`.","message":"In version 4.0.0, the behavior of `.ttl(key, 0)` and `stdTTL=0` was fixed. Previously, setting TTL to 0 would immediately delete the key. It now correctly sets an unlimited TTL.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Carefully consider the implications of `useClones`. For immutable data or read-only access, `true` (default) is safer. For performance-critical scenarios with mutable objects where you understand the risks, `false` can be used. Be aware that changing the default to `false` might introduce subtle bugs if not handled carefully.","message":"The `useClones` option (default: `true`) determines if stored values are deep-cloned. If `true`, you get a copy, preventing external mutations from affecting cached data. If `false`, you get a reference, which is faster but means cached objects can be mutated externally, potentially leading to unexpected behavior.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Ensure all keys passed to `set`, `get`, `del`, etc., are either strings or numbers. Convert other types to strings if necessary before caching.","message":"Keys must be `string` or `number` types since v4.1.0. Other types will throw an error during `set` operations.","severity":"gotcha","affected_versions":">=4.1.0"},{"fix":"Avoid relying on `enableLegacyCallbacks`. Migrate your code to use the synchronous API calls as soon as possible to prepare for v6.x.","message":"The `enableLegacyCallbacks` option, which re-enables callback support for compatibility with pre-v5 APIs, is marked for removal in v6.x.","severity":"deprecated","affected_versions":">=5.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Remove the callback argument and use the synchronous return value: `const value = myCache.get(key);`","cause":"Attempting to use callback-based API (`myCache.get(key, callback)`) after upgrading to v5.x, where callbacks were removed by default.","error":"TypeError: myCache.get is not a function (when using callbacks after v5)"},{"fix":"Convert your key to a string (e.g., `JSON.stringify(myObjectKey)` or `myObjectKey.id.toString()`) or ensure it's a number before passing it to cache methods.","cause":"Trying to use an object (or other non-string/non-number type) as a cache key.","error":"Error: Key type 'object' is not supported. Use 'string' or 'number'."},{"fix":"Increase the `maxKeys` option during initialization (`new NodeCache({ maxKeys: desiredLimit })`), implement a custom eviction strategy by manually deleting less important keys, or handle the error gracefully.","cause":"Attempting to add a new item to the cache when the `maxKeys` limit has been reached.","error":"Cache is full, cannot add new key (when maxKeys is set)"},{"fix":"Upgrade to `node-cache` version 5.0.2 or newer to ensure `deleteOnExpire: false` functions as intended, allowing you to handle expired items manually via the 'expired' event.","cause":"A bug in versions prior to 5.0.2 caused expired values to be deleted regardless of the `deleteOnExpire` setting.","error":"Values were still being deleted after expiration even with 'deleteOnExpire: false' (pre-v5.0.2)"}],"ecosystem":"npm"}