npm.io
2.2.0 • Published yesterday

flash-store

Licence
Apache-2.0
Version
2.2.0
Deps
2
Size
109 kB
Vulns
0
Weekly
0
Stars
21

flash-store

Powered by LMDB Powered by TypeScript ES Modules

NPM Version npm (next) GitHub Action TypeScript Downloads node

FlashStore provides persistent key-value storage with asynchronous and synchronous Map-like APIs. It uses LMDB in Node.js and Deno and IndexedDB in Chrome.

flash store

Requirements

The npm package is ESM-only. For Node.js development use Node.js 26 and npm 11 or newer. For Deno use Deno 2.9.8 or newer with local node_modules and permission to load the LMDB native addon. Chrome uses its built-in IndexedDB.

Examples

Try the following command

npm install
npm run demo

The basic function as follows:

import { FlashStore } from 'flash-store'

const flashStore = new FlashStore('flashstore.workdir')

await flashStore.set(1, 'a')
console.log(`key: 1, value: ${await flashStore.get(1)}`)
// Output: 'a'

await flashStore.delete(1)
console.log(`key: 1, value: ${await flashStore.get(1)}`)
// Output: undefined
await flashStore.close()
Deno

Install the package with deno install --node-modules-dir=auto npm:flash-store. Use import { FlashStore } from 'npm:flash-store' and run the program with deno run --node-modules-dir=auto --allow-read --allow-write --allow-env --allow-ffi=./node_modules app.ts. Grant --allow-sys=homedir if the program calls destroy() so Flash Store can check protected directories.

Chrome

Import only 'flash-store'; the build tool picks the build. Tools that use the browser export condition (and any runtime without a node condition, such as Cloudflare Workers) resolve it to IndexedDB, while Node.js, Deno, and Bun resolve it to LMDB. Applications can force a build with flash-store/browser or flash-store/node; libraries should not. For a page that loads modules directly, serve the installed package files and use an HTML import map to resolve the entry and its two bare imports:

<script type="importmap">
{
  "imports": {
    "flash-store/browser": "/node_modules/flash-store/dist/src/mod.js",
    "brolog": "/node_modules/brolog/dist/esm/src/mod.js"
  }
}
</script>

Serve the referenced JavaScript and the package's dist/package.json with their JavaScript and JSON content types, respectively.

import { FlashStore, FlashStoreSync } from 'flash-store/browser'

const store = new FlashStore('app-cache')
await store.set('theme', 'dark')
await store.close()

const cache = new FlashStoreSync('app-cache')
await cache.ready()
console.log(cache.get('theme'))
await cache.close()

The constructor takes a database name scoped to the current origin. Its operations wait for IndexedDB to open. destroy() deletes that named database and waits for other connections to release it. Flash Store connections close when Chrome requests an upgrade or deletion. A handle closed by that event rejects a later destroy(). Once you explicitly call close(), the handle stops receiving database events. A later destroy() uses the database name, which can refer to a replacement created by another tab. Call destroy() directly on an open handle when you intend to remove its database.

A synchronous cache sees its own writes and the snapshot restored by ready(). If another tab changes the database, reopen the cache to read the updated state. Browser data is subject to site storage quotas and eviction.

API Reference

FlashStore

FlashStore provides async set, get, has, delete, clear, forEach, and size, plus async iteration through entries, keys, and values. Keys are finite numbers or strings without null characters; values use JSON serialization. Numeric keys sort naturally before strings. Both backends enforce the default LMDB limit of 1978 encoded bytes per key. See the LMDB documentation. For arbitrary string identifiers in LMDB, encode embedded control characters and unpaired UTF-16 surrogates before storing them as keys.

Values are serialized with JSON.stringify and read back with JSON.parse. This is not a lossless round trip for every JavaScript value: for example, Date becomes a string, NaN and infinities become null, and properties whose values are undefined are omitted. Top-level undefined, circular objects, and BigInt cannot be stored. The TypeScript value type V is not validated against the decoded JSON, so it may not match the runtime value. Use JSON-compatible values and validate decoded data when its shape matters.

Async iteration uses a snapshot in key order. LMDB orders string keys by UTF-8 bytes, whereas Chromium IndexedDB orders strings by native UTF-16 code units. Chrome collects the matching records inside a single IndexedDB transaction before yielding the first result, so its memory use grows with the number of matches. For large datasets in browser environments, paginate queries with limit and range bounds. forEach awaits each callback sequentially and stops on the first error, rejecting its returned promise. FlashStoreSync.forEach remains synchronous.

Iteration accepts gt, gte, lt, lte, reverse, limit, or a string prefix. Do not combine a prefix with range bounds, or two bounds on the same side. A prefix scan seeks directly to matching string keys and stops after the last match, so it does not read unrelated entries. delete resolves to whether a key existed.

close() waits for outstanding writes. destroy() closes and deletes the entire database directory under Node.js and Deno, so use a dedicated directory. In Chrome it deletes the named IndexedDB database. After a successful destroy(), another call on the same handle has no effect. Both operations reject on failure.

FlashStoreSync

FlashStoreSync maintains a full in-memory Map and writes changes in order in the background. set() and delete() validate keys, and set() serializes the value immediately: invalid keys or non-JSON values throw without changing the cache, and later changes to a stored object are not persisted unless it is set again. The cache still holds the original object, so it reflects such changes until reopened. Await ready() before reading restored data and to observe write failures. After a detected write failure, further mutations throw; close and reopen the store to recover. Mutations queued before the failure is detected may remain in the cache without being persisted. close() and destroy() wait for queued writes and close the database even on failure. destroy() removes the backing store only if writes succeeded. Until ready() completes, reads and delete return values only reflect the cache loaded so far.

The cache iterates in its current insertion order, but reopening restores entries in storage key order. Mutations during restoration may also affect the cache order. The cache holds the values supplied to it; after reopening, values reflect the JSON round trip above.

Diagnostics

On Node.js and Deno the flash-store.operation diagnostics channel publishes { operation } after successful set, delete, and clear operations. Messages contain no keys, values, or paths. The existing exported log remains available; its configured log level determines what application data it logs.

Development

Node executes TypeScript directly. npm test runs type checking, Biome, and the Node unit tests. The same unit test files run with npm run test:unit:deno and npm run test:unit:browser. Install Chromium for the browser suite with npx playwright install chromium.

npm run test:integration and npm run test:integration:deno exercise raw LMDB and native diagnostics. npm run coverage:node, npm run coverage:deno, and npm run coverage:browser enforce independent line, branch, and function floors for each runtime adapter and shared sources. The coverage check fails if an executable production file in that scope is absent from the runtime report. CI uploads each runtime's LCOV and HTML reports. npm run test:pack verifies the installed package in Node, Deno, and Chromium and checks consumer type resolution. The Chromium smoke test covers both bundled and direct ESM loading.

Benchmark

Run npm run benchmark to compare FlashStore's public API with native LMDB using 5,000 entries and six paired trials. For example: npm run benchmark -- --count 10000 --duration 500 --trials 6 --dir /path/to/disk --memory-dir /dev/shm. Duration is the minimum sample length in milliseconds.

The report has three tables:

  • API overhead runs on memory-backed storage (/dev/shm by default on Linux) so fsync latency does not hide per-call costs. It measures seeded random reads, ordered iteration, and inserts and deletes, sequentially and in batches of 32. Reads and scans give every variant the same calibrated pass count; mutations repeat insert-then-delete cycles of 50 or 256 absent keys until each phase lasts at least --duration.
  • Diagnostics add one FlashStore behavior to native LMDB: an async call per read, an async generator per scanned entry, or the conditional remove(key, IF_EXISTS) that lets delete() report whether a key existed (a plain remove() resolves true even for absent keys). When a variant's ratio matches FlashStore's, that behavior explains the overhead. Each row also shows FlashStore and native LMDB throughput from the same trials.
  • Durable mutations run on --dir (the OS temporary directory by default) with fixed samples: 50 sequential and 256 batched inserts and deletes. Commit latency usually dominates, so similar numbers are expected.

When /dev/shm is unavailable, the memory mode is skipped; pass --memory-dir to choose another existing directory or --no-memory to skip it. The filesystem type is reported, and only tmpfs or ramfs is labeled as memory-backed. The memory mode checks free space first; lower --count for small memory filesystems.

Both engines use identical JSON bytes, default durability, and fresh databases preloaded in an untimed transaction. FlashStore uses its public async API; LMDB uses synchronous get()/getRange(), JSON decoding, asynchronous put(), and native remove(). This compares usable public APIs, not identical internal algorithms. Reads and scans are warm-cache measurements, not cold-storage performance. The first trial warms up and calibrates reads and scans; each mutation measurement has an untimed warm-up. Full contents and entry counts are validated outside timing; timed reads and scans consume an identical checksum, checked afterward.

The output shows median operations/second, reciprocal microseconds/operation (not latency percentiles), trial ranges, and all sample sizes and durations. Variants alternate order between trials. Ratios are medians of per-trial paired ratios. Paired ranges crossing 1 are labeled mixed/tied; ranges are descriptive, not confidence intervals. With 5,000 cached entries, ratios are close to worst-case overhead; larger datasets spend more time in LMDB.

Temporary databases are removed after each trial. Results depend on the machine and filesystem; there are no CI performance thresholds. The default workload targets less than a minute on the test machine, not on every filesystem. Run node --test scripts/benchmark.integration.test.ts to check the benchmark CLI, its option validation, and temporary-directory cleanup.

Document

See the documentation.

Version History

v2.0
  1. LMDB-backed storage, ESM-only packaging, and Node.js 26.

FAQ

Q: What's the difference between the flash-store and memory-card

Short answer:

  1. flash-store is for save data to local filesystem.
  2. memory-card is for save data to a distributed network storage, it can be serialized/deserialized safely with the minimum payload transfered by design.

Long answer:

flash-store and memory-card are all built by @huan, and they are all follow the ES6 Map API.

flash-store is using a no-sql local file database to maximum the performance, it can be used as a local database, or a local cache for whatever you want to cache from other API.

memory-card is using a local file to store data in JSON format by default, however, it supports more distributed methods and it can be serialized/deserialized safely with the minimum payload for transfer the data between networks (for example, it can serialize itself to only include the redis config and then deserialize it to restore a MemoryCard instance with the same data backend). Learn more from it's repository at here

Author

Huan LI (Huan Li) huan@chatie.io

Profile of Huan Li on StackOverflow

  • Code & Docs 2017-now Huan Li <huan@chatie.io>
  • Code released under the Apache-2.0 License
  • Docs released under Creative Commons

Keywords