csv-database
csv-database is a lightweight Node.js library offering a complete CRUD (Create, Read, Update, Delete) API, utilizing CSV files for data storage. Built with TypeScript and leveraging async/await, it provides native JavaScript object interaction, allowing developers to query and manipulate data using familiar object predicates. As of version 0.9.2, it is in active development, with a focus on stability for its upcoming 1.0 release. Key differentiators include its strong TypeScript typings, built-in model validation, and a focus on being "concurrency-ready" for file operations. It's designed for applications requiring simple, local data persistence without the overhead of a full relational or NoSQL database, making it suitable for smaller projects or configuration storage.
Common errors
-
Error: Field 'unknownField' is not part of the model.
cause Attempting to use a key in a predicate object (for `get`, `edit`, `delete`) that is not defined in the CSV database's model array.fixReview your database model definition and ensure all predicate keys exactly match a field in the model. E.g., if model is `['id', 'name']`, use `{ id: 1 }` not `{ userID: 1 }`. -
TypeError: csvdb is not a function
cause This usually occurs if `await` is missing when calling `csvdb` (it returns a Promise), or if using `require` without `.default` for a default ES module export.fixEnsure you `await` the `csvdb` call (e.g., `const db = await csvdb(...)`). If using CommonJS, use `const csvdb = require('csv-database').default;`. -
Error: EACCES: permission denied, unlink 'path/to/your/file.csv'
cause The Node.js process does not have the necessary file system permissions to create, read, write, or delete the specified CSV file.fixCheck the permissions of the directory where the CSV file is located. Ensure the user running the Node.js application has read/write/delete access to that directory.
Warnings
- gotcha The default delimiter used by `csv-database` is a semicolon (`;`), not the more common comma (`,`). If your CSV files use commas, you must explicitly specify the delimiter during database initialization.
- gotcha Predicates used in `get`, `edit`, and `delete` operations are strictly validated against the database's model. Providing a field in the predicate that is not defined in the model will result in an error.
- gotcha As `csv-database` is currently below version 1.0 (e.g., 0.9.2), its API may not be fully stable. Minor versions could introduce breaking changes as the library matures towards its stable release.
Install
-
npm install csv-database -
yarn add csv-database -
pnpm add csv-database
Imports
- csvdb
import { csvdb } from 'csv-database';import csvdb from 'csv-database';
- csvdb
const csvdb = require('csv-database');const csvdb = require('csv-database').default; - CsvDatabase
import { CsvDatabase } from 'csv-database';import csvdb, { CsvDatabase } from 'csv-database';
Quickstart
import csvdb, { CsvDatabase } from 'csv-database';
import path from 'path';
import fs from 'fs/promises';
interface User {
id: number;
name: string;
mail: string;
}
async function main() {
const filename = path.join(__dirname, 'users.csv');
// Ensure the file exists (or is created) and cleanup for demo
try { await fs.unlink(filename); } catch (e) { /* ignore */ }
const db: CsvDatabase<User> = await csvdb<User>(filename, ['id', 'name', 'mail']);
console.log('Database initialized.');
// Add data
await db.add([{ id: 1, name: 'johndoe', mail: 'john@example.com' }]);
await db.add({ id: 2, name: 'janedoe', mail: 'jane@example.com' });
console.log('Added two users.');
// Get all data
const allUsers = await db.get();
console.log('All users:', allUsers);
// Get data with predicate
const john = await db.get({ name: 'johndoe' });
console.log('John Doe:', john);
// Edit data
await db.edit({ name: 'johndoe' }, { mail: 'john.doe@newmail.com' });
const updatedJohn = await db.get({ id: 1 });
console.log('Updated John:', updatedJohn);
// Delete data
await db.delete({ id: 2 });
const remainingUsers = await db.get();
console.log('Remaining users after delete:', remainingUsers);
// Clean up the created file
await fs.unlink(filename);
console.log('Cleaned up users.csv');
}
main().catch(console.error);