Class: Storage

跨平台持久化存储适配器。 Cross-platform persistent storage adapter.

设计目标: Design goal:

  • 仿照 Web Storage (Storage) 接口设计
  • Modeled after Web Storage (Storage) interface
  • 统一 VPN App 脚本环境中的持久化读写接口
  • Unify persistence APIs across VPN app script environments

支持后端: Supported backends:

  • Surge/Loon/Stash/Egern/Shadowrocket: $persistentStore
  • Quantumult X: $prefs
  • Worker: 内存缓存(非持久化)
  • Worker: in-memory cache (non-persistent)
  • Node.js: 由 Node.js ESM 入口注入持久化后端
  • Node.js: persistent backend injected by the Node.js ESM entry

支持路径键: Supports path key:

  • @root.path.to.value

与 Web Storage 的已知差异: Known differences from Web Storage:

  • 支持 @key.path 深路径读写(Web Storage 原生不支持)
  • Supports @key.path deep-path access (not native in Web Storage)
  • removeItem/clear 并非所有平台都可用
  • removeItem/clear are not available on every platform
  • 读取时会尝试 JSON.parse,写入对象会 JSON.stringify
  • Reads try JSON.parse, writes stringify objects

https://developer.mozilla.org/en-US/docs/Web/API/Storage

https://developer.mozilla.org/zh-CN/docs/Web/API/Storage

Constructors

Constructor

new Storage(): Storage

Returns

Storage

Properties

data

static data: Record<string, any> = null

Worker / Node.js 环境下的内存数据缓存。 In-memory data cache for Worker / Node.js runtime.


dataFile

static dataFile: string = "box.dat"

Node.js 持久化文件名。 Data file name used in Node.js.


nodeBackend

static nodeBackend: object = null

Node.js ESM 入口注入的存储后端。 Storage backend injected by the Node.js ESM entry.

load

load: (dataFile) => Record<string, any>

Parameters
dataFile

string

Returns

Record<string, any>

write

write: (dataFile, data) => void

Parameters
dataFile

string

data

Record<string, any>

Returns

void

Methods

clear()

static clear(): boolean

清空存储。 Clear storage.

Returns

boolean


getItem()

static getItem(keyName, defaultValue?): any

读取存储值。 Read value from persistent storage.

Parameters

keyName

string

键名或路径键 / Key or path key.

defaultValue?

any = null

默认值 / Default value when key is missing.

Returns

any


removeItem()

static removeItem(keyName): boolean

删除存储值。 Remove value from persistent storage.

平台说明: Platform notes:

  • Quantumult X: $prefs.removeValueForKey
  • Surge: 通过 $persistentStore.write(null, keyName) 删除
  • 其余平台当前返回 false

Parameters

keyName

string

键名或路径键 / Key or path key.

Returns

boolean


setItem()

static setItem(keyName?, keyValue?): boolean

写入存储值。 Write value into persistent storage.

Parameters

keyName?

string = ...

键名或路径键 / Key or path key.

keyValue?

any = ...

写入值 / Value to store.

Returns

boolean