# @caruuto/cache

> A caching layer supporting Redis and filesystem caching

Latest version **3.6.0** (published 2026-06-21) · 0 weekly downloads

## Install

```sh
npm install @caruuto/cache
pnpm add @caruuto/cache
yarn add @caruuto/cache
bun add @caruuto/cache
```

## Health

**Score 55/100 (C)** — status: active.

Positive: no vulnerabilities; recently updated; high maintenance score.

Warnings: low downloads; no types; no esm support.

## Facts

| | |
|---|---|
| Version | 3.6.0 |
| Published | 2026-06-21 |
| First published | 2022-05-29 |
| Weekly downloads | 0 |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 13 |
| Unpacked size | 369 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Maintainers | jimlambie, woogz |

## Links

- npm: https://www.npmjs.com/package/@caruuto/cache
- Repository: https://github.com/caruuto/cache
- Issues: https://github.com/caruuto/cache/issues
- npm.io page: https://npm.io/package/@caruuto/cache

## Dependencies (13)

- [debug](https://npm.io/package/debug.md) ^2.6.1
- [redis](https://npm.io/package/redis.md) ^3.1.1
- [lokijs](https://npm.io/package/lokijs.md) ^1.5.3
- [mkdirp](https://npm.io/package/mkdirp.md) 1.0.4
- [ioredis](https://npm.io/package/ioredis.md) ^5.0.0
- [deepmerge](https://npm.io/package/deepmerge.md) ^4.3.1
- [streamifier](https://npm.io/package/streamifier.md) 0.1.1
- [redis-rstream](https://npm.io/package/redis-rstream.md) 0.1.2
- [redis-wstream](https://npm.io/package/redis-wstream.md) 0.2.5
- [stream-to-string](https://npm.io/package/stream-to-string.md) 1.1.0
- [recursive-readdir](https://npm.io/package/recursive-readdir.md) 2.1.1
- [node-redis-streamify](https://npm.io/package/node-redis-streamify.md) 0.1.6
- [remove-empty-directories](https://npm.io/package/remove-empty-directories.md) 0.0.1

## Recent versions

- 3.6.0 (latest) — 2026-06-21
- 3.5.0 — 2026-06-21
- 3.4.0 — 2026-06-21
- 3.3.1 — 2026-05-11
- 3.3.0 — 2026-05-11
- 3.2.0 — 2026-05-11
- 3.1.0 — 2025-01-10
- 3.0.2 — 2022-08-25
- 3.0.1 — 2022-08-25
- 3.0.0 — 2022-05-29

## README

# Cache

> A caching layer supporting Redis and filesystem caching.

- [Overview](#overview)
- [Install](#install)
- [Usage](#usage)
  - [Create Cache instance](#create-cache-instance)
  - [Add an item to the cache](#add-an-item-to-the-cache)
  - [Get an item from the cache](#get-an-item-from-the-cache)
  - [Example real world usage](#example-real-world-usage)
- [Configuration](#configuration)
  - [General Options](#general-options)
  - [Default Options](#default-options)
  - [Filesystem Caching](#filesystem-caching)
  - [Redis Caching](#redis-caching)
  - [Redis Cluster](#redis-cluster)
- [Cache Fallback](#cache-fallback)

## Overview

Removing the complexity involved in setting up two separate cache handlers for every project, Cache can use either the filesystem or a Redis instance to store and retrieve content.

## Install

```shell
npm install @caruuto/cache
```

## Usage

### Create Cache instance

```js
// require the module
const Cache = require('@caruuto/cache')

// setup the options for caching
// defaults if nothing specified:
// {
//   directory: {
//     enabled: true,
//     path: './cache'
//   },
//   redis: {
//     enabled: false
//   }
// }
const options = {
  ttl: 3600,
  directory: {
    enabled: false,
    path: './cache/'
  },
  redis: {
    enabled: true,
    host: '127.0.0.1',
    port: 6379
  }
}

const cache = new Cache(options)
```

### Add an item to the cache

#### `set(key, data)`

Returns a Promise that returns an empty String if successful, otherwise an Error.

The `data` argument can be a String, Buffer or Stream.

```js
let key = 'test-cached-item'
let data = 'test data'

cache
  .set(key, data)
  .then(() => {
    // do something
  })
  .catch((err) => {
    // Error
  })
```

### Get an item from the cache

#### `get(key)`

Returns a Promise that returns a Stream of the cached data if the key exists or an Error if it does not exist.
The error message returned is "The specified key does not exist".

```js
let key = 'test-cached-item'

cache
  .get(key)
  .then((stream) => {
    // do something with the stream
  })
  .catch((err) => {
    // err === "The specified key does not exist"
  })
```

### Example real world usage

```js
const express = require('express')
const app = express()
const Cache = require('@caruuto/cache')
const cache = new Cache()

app.get(function (req, res) {
  let key = req.url

  cache
    .get(key)
    .then((stream) => {
      // cached data found for req.url
      res.setHeader('X-Cache', 'HIT')
      stream.pipe(res)
    })
    .catch((err) => {
      // cached data not found for req.url
      let content = fetchContent()

      // cache the content
      cache.set(key, content).then(() => {
        res.setHeader('X-Cache', 'MISS')
        res.end(content)
      })
    })
})
```

## Configuraton

### General options

| Property | Description                                                       | Default | Example |
| -------- | ----------------------------------------------------------------- | ------- | ------- |
| ttl      | The time, in seconds, after which cached data is considered stale | true    | 3600    |

### Default options

A Cache instance can be created with no options, in which case the following options will be used:

```js
{
  "directory": {
    "enabled": true,
    "path": "./cache"
  },
  "redis": {
    "enabled": false
  }
}
```

### Filesystem caching

| Property           | Description                                                                                                                           | Default   | Example       |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------------- |
| enabled            | If true, caching is enabled using the following settings                                                                              | true      |
| path               | The absolute or relative path to the directory for cache files                                                                        | "./cache" | "/tmp/cache/" |
| extension          | (optional) The extension to use for cache files                                                                                       | none      | "json"        |
| directoryChunkSize | (optional) If set, cache files are stored in a series of subdirectories based on the cache key                                        | 0         | 5             |
| autoFlush          | If true, Cache will clear cache files that are older than the specified TTL setting, at the interval specified by `autoFlushInterval` | false     | true          |
| autoFlushInterval  | The period of time between clearing cache files (in seconds)                                                                          | 300       | 1800          |

### Redis caching

A set of options for both file and Redis caching _must_ be provided if you intend to use Redis as the cache store. This allows Cache
to [fallback to file caching](#cache-fallback) in the event of a Redis connection failure.

| Property | Description                                                                                                                                         | Default     | Example                             |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------- |
| enabled  | If true, caching is enabled using the following settings                                                                                            | false       | true                                |
| host     | The hostname or IP address of the Redis server                                                                                                      | "127.0.0.1" | "famous-coral-88226.upstash.io"     |
| port     | The port of the Redis server                                                                                                                        | 6379        | 9092                                |
| password | The password (or auth token) used to authenticate with the Redis server                                                                             | -           | "xxx"                               |
| tls      | If true, connects over TLS using default settings. Pass an object to supply custom TLS options. Many managed providers (e.g. Upstash) require this. | false       | `true` or `{ "servername": "..." }` |

```json
{
  "directory": {
    "enabled": true,
    "path": "./cache"
  },
  "redis": {
    "enabled": true,
    "host": "famous-coral-88226.upstash.io",
    "port": 6379,
    "password": "xxx",
    "tls": true
  }
}
```

### Redis Cluster

| Property   | Description                                                                                                                | Default  | Example                                                                    |
| ---------- | -------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------- |
| enabled    | If true, caching is enabled using the following settings                                                                   | false    | true                                                                       |
| cluster    | If true, Cache will connect caching is enabled using the following settings                                                | false    | true                                                                       |
| scaleReads | Specify where to send queries, to the masters, slaves, or a combination. See [Read-Write Splitting](#read-write-splitting) | "master" | "all"                                                                      |
| hosts      | When `cluster: true`, Cache uses this array of hosts to connect. Each array item must contain a `host` and `port`.         |          | `[{"host":"127.0.0.1", "port": 6379}, {"host":"127.0.0.1", "port": 6380}]` |

To connect to a Redis cluster an array of hosts must be specified, rather than a single host and port. `password` and `tls` (see above) are also supported in cluster mode and are applied to every node connection.

> The array does not need to contain all your cluster nodes, but a few so that if one is unreachable the next one will be tried. Cache will discover other nodes automatically when at least one node is connnected.

```json
{
  "directory": {
    "enabled": true,
    "path": "./cache"
  },
  "redis": {
    "enabled": true,
    "cluster": true,
    "scaleReads": "all",
    "hosts": [
      {
        "host": "127.0.0.1",
        "port": 6379
      },
      {
        "host": "127.0.0.1",
        "port": 6383
      }
    ]
  }
}
```

#### Read-Write Splitting

A typical Redis cluster contains three or more masters and several slaves for each master. It's possible to scale out Redis cluster by sending read queries to slaves and write queries to masters by setting the `scaleReads` option.

`scaleReads` is "master" by default, which means no queries will be sent to slaves. The other available options:

- "all": Send write queries to masters and read queries to masters or slaves randomly.
- "slave": Send write queries to masters and read queries to slaves.

**For example, with `scaleReads: "slave"`:**

```js
cache.set('foo', 'bar') // This query will be sent to one of the masters.
cache.get('foo', (err, res) => {
  // This query will be sent to one of the slaves.
})
```

**Note:** In the code snippet above, the result may not be equal to "bar" because of the lag of replication between the master and slaves.

## Cache Fallback

In the case of a Redis connection failure, Cache will attempt to reconnect four times before switching to file caching.
After a configurable period (default 5 minutes), an attempt will be made to reconnect to Redis and if successful Cache will resume
using Redis as the cache store.

---
_Source: https://npm.io/package/@caruuto/cache · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
