Skip to content

Repository files navigation

node-sqlite-map

A persistent Map-compatible API backed by SQLite using Node.js's built-in node:sqlite module. No external database dependencies — just a file (or :memory:).

Requirements

  • Node.js >= 22.5.0 (for node:sqlite)

Installation

npm install node-sqlite-map
# or
pnpm add node-sqlite-map

Quick Start

import{SqliteMap}from"node-sqlite-map"constmap=newSqliteMap("./data.db")map.set("user:1",{name: "Kyle",role: "admin"})map.get("user:1")// { name: "Kyle", role: "admin" }map.has("user:1")// truemap.size// 1

Use :memory: for an in-memory database that does not persist:

constmap=newSqliteMap(":memory:")

API

Constructor

newSqliteMap<Kextendsstring,V>(path: string,options?: DatabaseSyncOptions)
ParameterTypeDescription
pathstringPath to SQLite database file, or ":memory:"
optionsDatabaseSyncOptionsOptional Node.js DatabaseSync options

Core Methods

set(key, value): this

Inserts or replaces a key-value pair. Returns this for chaining.

map.set("a",1).set("b",2).set("c",3)

get(key): V | undefined

Returns the value for the key, or undefined if not found.

map.get("a")// 1map.get("z")// undefined

has(key): boolean

Returns true if the key exists.

map.has("a")// true

delete(key): boolean

Removes the entry. Returns true if it existed, false otherwise.

map.delete("a")// truemap.delete("a")// false

clear(): void

Removes all entries.

map.clear()map.size// 0

getOrInsert(key, defaultValue): V

Returns the existing value if the key exists, otherwise inserts defaultValue and returns it.

map.getOrInsert("count",0)// inserts 0 and returns 0map.getOrInsert("count",99)// returns 0 (already exists)

getOrInsertComputed(key, callbackFn): V

Like getOrInsert but the default value is computed lazily via a callback — only called if the key is missing.

map.getOrInsertComputed("slug",(key)=>key.toLowerCase().replace(" ","-"))

Iteration

All iteration methods reflect the insertion order of keys.

keys(): IterableIterator<K>

for(constkeyofmap.keys())console.log(key)// "a", "b", "c"console.log([...map.keys()])// ["a", "b", "c"]

values(): IterableIterator<V>

console.log([...map.values()])// [1, 2, 3]

entries(): IterableIterator<[K, V]>

console.log([...map.entries()])// [["a", 1], ["b", 2], ["c", 3]]

forEach(callback): void

map.forEach((value,key,map)=>{console.log(key,value)})

[Symbol.iterator]()

Makes the map directly iterable — equivalent to entries().

for(const[key,value]ofmap){console.log(key,value)}

Properties

size: number

Returns the number of entries.

map.size// 3

Serialization

toJSON(): Record<string, V>

Returns a plain object representation. Called automatically by JSON.stringify.

map.set("x",1)map.toJSON()// { x: 1 }JSON.stringify(map)// '{"x":1}'

[Symbol.toStringTag]: string

Returns "SqliteMap".

Object.prototype.toString.call(map)// "[object SqliteMap]"

Type Parameters

SqliteMap<Kextendsstring,V>
ParameterConstraintDescription
KstringKey type — must be a string
VanyValue type — must be JSON-serializable

Values are stored as JSON strings internally, so any JSON-serializable value is supported: objects, arrays, numbers, booleans, strings, null.

Examples

Persistent cache

constcache=newSqliteMap<string,{data: unknown;expiresAt: number}>("./cache.db")cache.getOrInsertComputed("api:users",()=>({data: fetchUsers(),expiresAt: Date.now()+60_000}))

Counting

consthits=newSqliteMap<string,number>("./hits.db")hits.getOrInsert("/home",0)hits.set("/home",(hits.get("/home")??0)+1)

Spreading / converting

// To plain objectconstobj=sqliteMap.toJSON()// To native Mapconstnative=newMap(sqliteMap.entries())// From array of entriesfor(const[k,v]ofentries)sqliteMap.set(k,v)

Differences from native Map

FeatureMapSqliteMap
Persistence❌ In-memory only✅ File-backed
Key typeAnystring only
Value typeAnyJSON-serializable
Iteration orderInsertion orderInsertion order
JSON.stringify{} (empty)✅ Full object

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links & Community

ResourceURL
GitHub repositoryhttps://github.com/xcfio/node-sqlite-map
npm packagehttps://www.npmjs.com/package/node-sqlite-map
Homepagehttps://github.com/xcfio/node-sqlite-map#readme
Bug reportshttps://github.com/xcfio/node-sqlite-map/issues

Discord

Join the community on Discord for help, and discussion:

https://discord.gg/FaCCaFM74Q


Made with ❤️ by xcfio

About

Persistent SQLite-backed Map for Node.js — zero dependencies, drop-in replacement for Map with data that survives restarts.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages