keyv-file

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

keyv-file

keyv-file

keyv-file is a fast, JSON-based storage adapter for Keyv. It is specifically optimized for performance through asynchronous batch writing and automatic background cleanup of expired data.

keyv-file 是一款为Keyv打造的基于JSON的快速存储适配器。它通过异步批量写入和自动后台清理过期数据的方式,针对性能进行了专门优化。

Configuration Options

配置选项

When initializing
KeyvFile
, you can fine-tune its behavior using the following options:
OptionDefault ValueDescription
filename
${os.tmpdir()}/keyv-file/default.json
The path where your data is persisted.
expiredCheckDelay
86400000
(24h)
Interval (ms) to scan and purge expired keys from the file.
writeDelay
100
Delay (ms) to batch multiple write operations, reducing disk I/O.
encode
JSON.stringify
Custom serialization function.
decode
JSON.parse
Custom deserialization function.

初始化
KeyvFile
时,你可以通过以下选项调整其行为:
选项默认值描述
filename
${os.tmpdir()}/keyv-file/default.json
数据持久化的存储路径。
expiredCheckDelay
86400000
(24小时)
扫描并清理文件中过期键的时间间隔(毫秒)。
writeDelay
100
批量处理多次写入操作的延迟时间(毫秒),用于减少磁盘I/O。
encode
JSON.stringify
自定义序列化函数。
decode
JSON.parse
自定义反序列化函数。

Usage Patterns

使用模式

1. Standard Keyv Integration

1. 标准Keyv集成方式

The most common way to use it is as a store for the main Keyv instance.
javascript
const Keyv = require('keyv')
const { KeyvFile } = require('keyv-file')

const keyv = new Keyv({
  store: new KeyvFile({
    filename: './data/cache.json',
    writeDelay: 50 // Faster writes for high-frequency updates
  })
});
最常见的用法是将其作为主Keyv实例的存储介质。
javascript
const Keyv = require('keyv')
const { KeyvFile } = require('keyv-file')

const keyv = new Keyv({
  store: new KeyvFile({
    filename: './data/cache.json',
    writeDelay: 50 // Faster writes for high-frequency updates
  })
});

2. The "Field" Pattern (Direct Usage)

2. 「字段」模式(直接使用)

You can use
KeyvFile
directly and utilize
makeField
for a more declarative, type-safe API.
typescript
import KeyvFile, { makeField } from 'keyv-file'

class MyDatabase extends KeyvFile {
  constructor() {
    super({ filename: './db.json' })
  }

  // Creates a dedicated helper for a specific key
  userSettings = makeField(this, 'user_settings_key')
}

const db = new MyDatabase()
await db.userSettings.set({ theme: 'dark' })
const settings = await db.userSettings.get({ theme: 'light' }) // returns default if empty
你可以直接使用
KeyvFile
,并借助
makeField
实现更具声明式、类型安全的API。
typescript
import KeyvFile, { makeField } from 'keyv-file'

class MyDatabase extends KeyvFile {
  constructor() {
    super({ filename: './db.json' })
  }

  // 为特定键创建专用的操作助手
  userSettings = makeField(this, 'user_settings_key')
}

const db = new MyDatabase()
await db.userSettings.set({ theme: 'dark' })
const settings = await db.userSettings.get({ theme: 'light' }) // 为空时返回默认值