{"id":16403,"library":"json-file-database","title":"JSON File Database for Node.js","description":"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.","status":"active","version":"2.0.3","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","lightweight","node","database","json","typescript"],"install":[{"cmd":"npm install json-file-database","lang":"bash","label":"npm"},{"cmd":"yarn add json-file-database","lang":"bash","label":"yarn"},{"cmd":"pnpm add json-file-database","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"const connect = require('json-file-database').connect","symbol":"connect","correct":"import { connect } from 'json-file-database'"},{"note":"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.","wrong":"import { ConnectOptions } from 'json-file-database'","symbol":"ConnectOptions","correct":"import type { ConnectOptions } from 'json-file-database'"},{"note":"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.","wrong":"import { CollectionConfig } from 'json-file-database'","symbol":"CollectionConfig","correct":"import type { CollectionConfig } from 'json-file-database'"}],"quickstart":{"code":"import { connect } from 'json-file-database'\n\n/**\n * Define the shape of your data. It must include the primary key property.\n */\ntype User = { id: number, name: string, email: string }\n\n/**\n * Connect to the database file. If it doesn't exist, it will be created.\n * The `init` property provides initial data if the file is new.\n */\nconst db = connect({\n  file: './my-app-db.json',\n  init: {\n    users: [\n      { id: 1, name: 'Alice', email: 'alice@example.com' },\n      { id: 2, name: 'Bob', email: 'bob@example.com' },\n    ],\n    products: [\n      { id: 101, name: 'Laptop', price: 1200 },\n    ]\n  }\n})\n\n/**\n * Get a typed collection instance, specifying the data type and primary key.\n * For v2+, the `primaryKey` option is mandatory if it's not 'id'.\n */\nconst users = db<User>({\n  name: 'users',\n  primaryKey: 'id',\n})\n\n// --- Perform CRUD operations ---\n\n// Find by primary key\nconsole.log('User with id 1:', users.find({ id: 1 }))\n\n// Insert a new user\nconst newUser: User = { id: 3, name: 'Charlie', email: 'charlie@example.com' }\nconsole.log('Inserting new user:', users.insert(newUser))\n\n// List all users\nconsole.log('All users:', Array.from(users))\n\n// Update an existing user\nconsole.log('Updating user 1:', users.update({ id: 1, name: 'Alicia', email: 'alicia@example.com' }))\n\n// Remove a user\nconsole.log('Removing user 2:', users.remove({ id: 2 }))\n\n// Verify the changes\nconsole.log('Users after operations:', Array.from(users))\n","lang":"typescript","description":"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."},"warnings":[{"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.","message":"Version 2.x introduced a breaking change requiring explicit specification of the `primaryKey` when defining a collection. Previously, it defaulted to 'id'.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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.","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`.","error":"TypeError: (0 , json_file_database__WEBPACK_IMPORTED_MODULE_0__.connect) is not a function"},{"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' })`.","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.","error":"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>'."},{"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.","cause":"Attempting to insert an object into a collection where an object with the same `primaryKey` value already exists.","error":"Error: The primary key 'X' already exists. Cannot insert duplicate."}],"ecosystem":"npm"}