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-databaseVerified import paths — ran on the pinned version, not inferred.
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.
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.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.
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.
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.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' })`.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.
No dependency data recorded yet.