/node-local-storage

A NodeJS ponyfill for the Storage API, utilizing SQLite

Primary LanguageTypeScriptMIT LicenseMIT

@idleberg/local-storage

A NodeJS ponyfill for the Storage API, utilizing SQLite.

License Version Build

Features

  • zero dependencies
  • fully API compatible to both, localStorage and sessionStorage
  • persists data across sessions
  • supports storage events

Note

This module depends on the experimental node:sqlite module included in NodeJS v22.5 and later.

Installation

npm install @idleberg/local-storage

Usage

API

createLocalStorage

Usage: createLocalStorage(dbFile: string)
Returns: [Storage, EventEmitter]

Creates an instance of the localStorage API, and a corresponding EventEmitter.

Example:

import { createLocalStorage } from "@idleberg/local-storage";

const [localStorage, emitter] = createLocalStorage("./db.sqlite");

// Listen for storage changes
emitter.on("storage", console.log);

createSessionStorage

Usage: createSessionStorage()
Returns: [Storage, EventEmitter]

Creates an instance of the sessionStorage API, and a corresponding EventEmitter.

Example:

import { createSessionStorage } from "@idleberg/local-storage";

const [sessionStorage, emitter] = createSessionStorage();

// Listen for storage changes
emitter.on("storage", console.log);

createStorages

Usage: createStorages(dbFile: string)
Returns: { sessionStorage, localStorage, emitter }

Creates instances of both, sessionStorage and localStorage, as well as a corresponding EventEmitter.

Example:

import { createStorages } from "@idleberg/local-storage";

const { sessionStorage, localStorage, emitter } = createStorages("./db.sqlite");

// Listen for storage changes
emitter.on("storage", console.log);

Storage (Advanced Usage)

Usage: new Storage(filePath: string | ':memory:', options: StorageEventOptions)

This class is used internally by the above factory functions. Instantiating it class allows you more control over the EventEmitter, e.g. you could re-use an existing one from your application code.

Example:

import { Storage } from "@idleberg/local-storage";
import EventEmitter from "events";

const myEmitter = new EventEmitter();

const localStorage = new Storage("./db.sqlite", {
    emitter: myEmitter,
});

// Listen for storage changes
myEmitter.on("storage", console.log);

Related

License

This work is licensed under The MIT License.