npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@eljs/cache

v1.3.2-alpha.0

Published

An intelligent caching system with zero-configuration setup and smart cleanup capabilities.

Downloads

151

Readme

@eljs/cache

An intelligent caching system with zero-configuration setup and smart cleanup capabilities.

NPM Version NPM Downloads License

✨ Features

  • 🚀 Zero Configuration - Works out of the box with sensible defaults
  • High Performance - Memory + disk dual-layer caching
  • 🧹 Smart Cleanup - Automatic cleanup of expired and invalid caches
  • 🔒 Type Safety - Full TypeScript support with generics
  • 📊 Observable - Built-in statistics and monitoring
  • 🎯 Flexible - Customizable key generation, serialization, and validation
  • 🛡️ Robust - Intelligent cache invalidation and error handling

📦 Installation

# Using pnpm (recommended)
pnpm add @eljs/cache

# Using yarn
yarn add @eljs/cache

# Using npm
npm install @eljs/cache -S

🚀 Quick Start

Basic Usage

import { Cache } from '@eljs/cache'

// Create cache instance
const cache = new Cache<string>()

// File-based caching
await cache.set('./config.json', 'cached data')
const data = await cache.get('./config.json')

// Data-based caching
await cache.setByData('my data')
const result = await cache.getByKey('generated-key')

Type-Safe Caching (Recommended)

interface UserData {
  id: string
  name: string
  email: string
  lastUpdated: number
}

// Create typed cache instance
const userCache = new Cache<UserData>({
  cacheDir: './user-cache',
  ttlDays: 1,
})

// Type-safe operations
const userData: UserData = {
  id: '123',
  name: 'John Doe',
  email: '[email protected]',
  lastUpdated: Date.now(),
}

await userCache.setByData(userData)
const cachedUser = await userCache.getByKey('user-123') // Type: UserData | null

📖 API Reference

Cache Constructor

new Cache<T>(options?: CacheOptions<T>)

interface CacheOptions<T> {
  /** Whether to enable caching (default: true) */
  enabled?: boolean
  /** Cache directory path (default: os.tmpdir() + '/.eljs-cache') */
  cacheDir?: string
  /** Cache time-to-live in days (default: 7) */
  ttlDays?: number
  /** Whether to automatically clean up expired files on startup (default: true) */
  autoCleanup?: boolean
  /** Maximum number of cache files (default: 1000) */
  maxFiles?: number
  /** Custom serializer for data persistence */
  serializer?: CacheSerializer<T>
  /** Custom key generation function */
  keyGenerator?: CacheKeyGenerator<T>
  /** Custom validator for cache validation */
  validator?: CacheValidator<T>
}

File-Based Caching Methods

get() - Get Cached Data by File Path

async get(filePath: string): Promise<T | null>

Features:

  • Automatically validates file modification time, size, and content hash
  • Returns null if cache is expired, invalid, or not found
  • Supports both memory and disk cache layers

Example:

const config = await cache.get('./app.config.json')
if (config) {
  console.log('Cache hit:', config)
} else {
  console.log('Cache miss - need to load from source')
}

set() - Set Cache Data for File Path

async set(filePath: string, data: T): Promise<void>

Caches data associated with a specific file path, including file metadata for validation.

Data-Based Caching Methods

getByKey() - Get Cached Data by Key

async getByKey(key: string): Promise<T | null>

setByData() - Cache Arbitrary Data

async setByData(data: T, metadata?: { timestamp?: number }): Promise<void>

Example:

// Cache arbitrary data
await cache.setByData({ userId: '123', preferences: {...} })

// Get data by generated key
const cachedData = await cache.getByKey('generated-key')

Cache Management Methods

getStats() - Get Cache Statistics

async getStats(): Promise<CacheStats>

interface CacheStats {
  hits: number        // Cache hit count
  misses: number      // Cache miss count
  files: number       // Number of cache files
  hitRate: number     // Hit rate (0-1)
  diskUsage: number   // Disk usage in bytes
}

Example:

const stats = await cache.getStats()
console.log(`Hit rate: ${(stats.hitRate * 100).toFixed(1)}%`)
console.log(`Disk usage: ${(stats.diskUsage / 1024 / 1024).toFixed(2)}MB`)

cleanup() - Clean Up Expired Cache

async cleanup(): Promise<CleanupResult>

interface CleanupResult {
  removed: number      // Number of files removed
  totalSize: number    // Space freed in bytes
  errors: string[]     // Error messages
}

clear() - Clear All Cache

async clear(): Promise<void>

Clears both memory and disk cache completely.

🎯 Customization

Custom Key Generator

const cache = new Cache<UserData>({
  keyGenerator: user => {
    // Generate unique key based on user data
    return `user-${user.id}-${user.email}`
  },
})

Custom Serializer

import { deflateSync, inflateSync } from 'zlib'

const cache = new Cache<any>({
  serializer: {
    serialize: data => {
      // Compress data before saving
      const json = JSON.stringify(data)
      return deflateSync(json).toString('base64')
    },
    deserialize: compressed => {
      // Decompress data after loading
      const buffer = Buffer.from(compressed, 'base64')
      const json = inflateSync(buffer).toString()
      return JSON.parse(json)
    },
  },
})

Custom Validator

const cache = new Cache<ApiResponse>({
  validator: async (entry, filePath) => {
    // Custom validation logic
    const isRecent = Date.now() - entry.timestamp < 3600000 // 1 hour
    const hasValidData = entry.data && entry.data.status === 'success'
    return isRecent && hasValidData
  },
})