Registry / database / json-file-database

json-file-database

JSON →
library2.0.3jsnpmunverified

json-file-database is a lightweight, TypeScript-first file-system-based database designed for Node.js projects that don't require the overhead of a traditional database server. It stores data directly in JSON files, abstracting away the complexities of `fs` and `JSON.parse`/`JSON.stringify` operations. The current stable version is 2.0.3, which introduced breaking changes to allow for a customizable primary key beyond just 'id'. The library differentiates itself by offering pure TypeScript support for fewer type-related errors, debounced writes to minimize disk I/O, and `O(log n)` time complexity for data operations through binary search, making it efficient for small to medium-sized datasets. It's suitable for prototyping, small applications, or configuration management where a simple, local persistence layer is preferred.

npm install json-file-database
INSTALL
IMPORT
SIG · JSON-FILE-DATABASE
J
json-file-database
databasejavascriptv2.0.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

connect
import { connect } from 'json-file-database'
const connect = require('json-file-database').connect
The `connect` function is the primary entry point. `json-file-database` is a modern, TypeScript-first package and is primarily used with ESM imports. CommonJS `require` might lead to issues or require specific configuration for transpilation.
ConnectOptions
import type { ConnectOptions } from 'json-file-database'
import { ConnectOptions } from 'json-file-database'
Use `import type` for importing interfaces or types to ensure they are removed during transpilation, preventing runtime errors in some environments and clarifying intent. This type defines the configuration object for the `connect` function.
CollectionConfig
import type { CollectionConfig } from 'json-file-database'
import { CollectionConfig } from 'json-file-database'
Use `import type` for importing interfaces. This type defines the configuration for a specific collection, including its `name` and the `primaryKey` property. It's essential for properly configuring and typing collections within the database instance.

This quickstart demonstrates how to connect to a JSON file database, initialize it with data, create a typed collection, and perform basic CRUD (Create, Read, Update, Delete) operations using the library's API.

import { connect } from 'json-file-database' /** * Define the shape of your data. It must include the primary key property. */ type User = { id: number, name: string, email: string } /** * Connect to the database file. If it doesn't exist, it will be created. * The `init` property provides initial data if the file is new. */ const db = connect({ file: './my-app-db.json', init: { users: [ { id: 1, name: 'Alice', email: 'alice@example.com' }, { id: 2, name: 'Bob', email: 'bob@example.com' }, ], products: [ { id: 101, name: 'Laptop', price: 1200 }, ] } }) /** * Get a typed collection instance, specifying the data type and primary key. * For v2+, the `primaryKey` option is mandatory if it's not 'id'. */ const users = db<User>({ name: 'users', primaryKey: 'id', }) // --- Perform CRUD operations --- // Find by primary key console.log('User with id 1:', users.find({ id: 1 })) // Insert a new user const newUser: User = { id: 3, name: 'Charlie', email: 'charlie@example.com' } console.log('Inserting new user:', users.insert(newUser)) // List all users console.log('All users:', Array.from(users)) // Update an existing user console.log('Updating user 1:', users.update({ id: 1, name: 'Alicia', email: 'alicia@example.com' })) // Remove a user console.log('Removing user 2:', users.remove({ id: 2 })) // Verify the changes console.log('Users after operations:', Array.from(users))
Debug
Known issues
breakingVersion 2.x introduced a breaking change requiring explicit specification of the `primaryKey` when defining a collection. Previously, it defaulted to 'id'.
fix
When initializing a collection via `db<T>({})`, ensure you pass the `primaryKey` option, e.g., `db<User>({ name: 'users', primaryKey: 'id' })`. If your data uses a different unique identifier, specify that property name.
affects: >=2.0.0
gotchaThe `init` property in the `connect` function is only applied if the specified database file does not exist. If the file already exists, the `init` data is ignored, and the existing file's content is used.
fix
Be aware that `init` is for first-time setup. To reset the database for development, manually delete the `db.json` file. For production, ensure your initialization logic handles existing data appropriately, perhaps by performing migrations or checks.
affects: >=1.0.0
gotchaElements stored in collections must have a unique property designated as the `primaryKey`. Inserting an element with a duplicate `primaryKey` value will result in a failed insertion or an error, as the library uses this key for uniqueness and sorting.
fix
Ensure all objects you insert or update into a collection have a unique value for the property specified as the `primaryKey`. Validate uniqueness before insertion, or handle the `false` return value from `insert` and `update` methods indicating failure.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: (0 , json_file_database__WEBPACK_IMPORTED_MODULE_0__.connect) is not a function
This error typically occurs when attempting to use a CommonJS `require` statement or an incorrect import syntax in an environment that expects ESM (ECMAScript Modules) for `json-file-database`.
fix
Ensure your project uses `import { connect } from 'json-file-database'` syntax. If using Node.js, ensure your `package.json` has `"type": "module"` or you are saving your files with a `.mjs` extension for ESM support. If using `require`, you might need to configure your bundler (e.g., Webpack, Rollup) or Babel to handle ESM modules correctly.
Argument of type '{ name: string; }' is not assignable to parameter of type 'CollectionConfig<T>'. Property 'primaryKey' is missing in type '{ name: string; }' but required in type 'CollectionConfig<T>'.
Since version 2.x, the `primaryKey` option is mandatory when calling `db<T>()` to define a collection, and this TypeScript error indicates it's missing.
fix
Add the `primaryKey` property to your collection configuration object, specifying the name of the property that acts as the unique identifier for elements in that collection. For example: `db<User>({ name: 'users', primaryKey: 'id' })`.
Error: The primary key 'X' already exists. Cannot insert duplicate.
Attempting to insert an object into a collection where an object with the same `primaryKey` value already exists.
fix
Before inserting, check if an element with the desired `primaryKey` already exists using `collection.has()`. If you intend to update, use `collection.update()` instead of `collection.insert()`. The `insert` method returns `false` if a duplicate exists, allowing for programmatic handling.
Upgrade
Version history
2.0.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
11 hits · last 30 days
node
10
Resources
json-file-database — npm install json-file-database · libregistry