Memory Storage for node-ts-cache

4.4.0 · active · verified Tue Apr 21

node-ts-cache-storage-memory is a dedicated in-memory storage module for the node-ts-cache library, designed to provide fast, local caching capabilities within Node.js applications. It is currently stable, with version 4.4.0 being the latest as of April 2026, and follows an active release cadence addressing bug fixes and performance enhancements. A key differentiator is its seamless integration with the node-ts-cache decorator-based caching system and the introduction of an 'enqueue' feature in v4.3.4 to prevent thundering herd problems by ensuring the original method is called only once even under high concurrency. This package focuses solely on in-memory storage, contrasting with other node-ts-cache storage modules like Redis or file-based options, and is primarily intended for scenarios where persistent or distributed caching is not required.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to set up and use `MemoryStorage` with `node-ts-cache` decorators, including basic caching and TTL expiration.

import { Cache, CacheContainer } from "node-ts-cache";
import { MemoryStorage } from "node-ts-cache-storage-memory";

const userCache = new CacheContainer(new MemoryStorage());

class MyService {
    // Simulate a network call or database query
    private async fetchUsersFromAPI(): Promise<string[]> {
        console.log('Fetching users from API...');
        return new Promise(resolve => setTimeout(() => resolve([`Max-${Date.now()}`, 'User']), 100));
    }

    @Cache(userCache, { ttl: 60 }) // Cache for 60 seconds
    public async getUsers(): Promise<string[]> {
        return this.fetchUsersFromAPI();
    }
}

async function runExample() {
    const service = new MyService();

    console.log('First call:');
    let users1 = await service.getUsers();
    console.log(users1);

    console.log('Second call (should be cached):');
    let users2 = await service.getUsers();
    console.log(users2);

    await new Promise(resolve => setTimeout(resolve, 61 * 1000)); // Wait for cache to expire

    console.log('Third call after TTL (should re-fetch):');
    let users3 = await service.getUsers();
    console.log(users3);
}

runExample();

view raw JSON →