database-js CSV Driver

1.0.0 · maintenance · verified Wed Apr 22

database-js-csv is a driver designed to integrate CSV files into the database-js ecosystem, allowing developers to perform SQL-like queries directly on CSV data. It operates as a wrapper around the jl-sql-api package, which provides the core SQL parsing functionality for JavaScript object streams. The overarching database-js project aims to offer a unified, promise-based interface for various data sources, including traditional SQL databases, JSON, Excel, and CSV, via standardized connection strings. While the core database-js library (version 0.5.1) and its underlying jl-sql-api haven't seen significant updates since mid-2021, indicating a maintenance phase, database-js-csv itself is at version 1.0.0. The primary advantage of this package lies in its ability to enable SQL querying on flat-file data, simplifying data access without requiring a dedicated database server.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a CSV file, performing a SELECT query with a prepared statement, inserting data, and then querying all data, including necessary setup and cleanup.

const fs = require('fs');
const { Database } = require('database-js');

// IMPORTANT: Require the driver to register it with database-js
require('database-js-csv');

const csvContent = `user_name,email,role\nsecret_user,secret@example.com,admin\nnot_so_secret_user,notsosecret@example.com,user\n`;
const csvFilePath = './test.csv';

// Create a dummy CSV file for the example
fs.writeFileSync(csvFilePath, csvContent);

(async () => {
    let connection;
    try {
        // The 'csv:///' prefix activates the database-js-csv driver
        connection = new Database(`csv://${csvFilePath}?headers=true&overwriteOnExecute=true`);
        
        let statement = await connection.prepareStatement("SELECT user_name, email FROM CSV WHERE user_name = ?");
        let rows = await statement.query('not_so_secret_user');
        console.log('Query result for not_so_secret_user:', rows);

        statement = await connection.prepareStatement("INSERT INTO CSV (user_name, email, role) VALUES (?, ?, ?)");
        await statement.execute('new_user', 'new@example.com', 'guest');
        console.log('Inserted new user.');

        // Query all data to see the inserted user
        statement = await connection.prepareStatement("SELECT * FROM CSV");
        rows = await statement.query();
        console.log('All data after insert:', rows);

    } catch (error) {
        console.error('Error:', error);
    } finally {
        if (connection) {
            await connection.close();
        }
        // Clean up the dummy CSV file
        fs.unlinkSync(csvFilePath);
        console.log('Cleaned up test.csv');
    }
})();

view raw JSON →