JSON File Database for Node.js
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.
Common errors
-
TypeError: (0 , json_file_database__WEBPACK_IMPORTED_MODULE_0__.connect) is not a function
cause 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`.fixEnsure 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>'.cause 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.fixAdd 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.
cause Attempting to insert an object into a collection where an object with the same `primaryKey` value already exists.fixBefore 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.
Warnings
- breaking Version 2.x introduced a breaking change requiring explicit specification of the `primaryKey` when defining a collection. Previously, it defaulted to 'id'.
- gotcha The `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.
- gotcha Elements 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.
Install
-
npm install json-file-database -
yarn add json-file-database -
pnpm add json-file-database
Imports
- connect
const connect = require('json-file-database').connectimport { connect } from 'json-file-database' - ConnectOptions
import { ConnectOptions } from 'json-file-database'import type { ConnectOptions } from 'json-file-database' - CollectionConfig
import { CollectionConfig } from 'json-file-database'import type { CollectionConfig } from 'json-file-database'
Quickstart
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))