csv-database

0.9.2 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a CSV database, add, retrieve, edit, and delete records, and clean up the created file.

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);

view raw JSON →