{"id":16328,"library":"database-js-csv","title":"database-js CSV Driver","description":"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.","status":"maintenance","version":"1.0.0","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","database-js","csv"],"install":[{"cmd":"npm install database-js-csv","lang":"bash","label":"npm"},{"cmd":"yarn add database-js-csv","lang":"bash","label":"yarn"},{"cmd":"pnpm add database-js-csv","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core database-js library providing the Connection interface and driver management.","package":"database-js"},{"reason":"Underlying SQL parsing engine for object streams, wrapped by this driver.","package":"jl-sql-api"}],"imports":[{"note":"The core database-js library primarily uses CommonJS `require` syntax. For CSV access, ensure `database-js-csv` is also required for its side effects (driver registration).","wrong":"import { Connection } from 'database-js'","symbol":"Connection","correct":"const Connection = require('database-js').Connection;"},{"note":"The `Database` constructor is the primary entry point for creating connections, invoked after `database-js-csv` has registered its driver.","wrong":"import { Database } from 'database-js'","symbol":"Database","correct":"const { Database } = require('database-js');"},{"note":"The `database-js-csv` package must be explicitly `require()`d (even without assigning to a variable) to register itself as a driver with `database-js`.","wrong":"import 'database-js-csv';","symbol":"Side-effect import for driver registration","correct":"require('database-js-csv');"}],"quickstart":{"code":"const fs = require('fs');\nconst { Database } = require('database-js');\n\n// IMPORTANT: Require the driver to register it with database-js\nrequire('database-js-csv');\n\nconst csvContent = `user_name,email,role\\nsecret_user,secret@example.com,admin\\nnot_so_secret_user,notsosecret@example.com,user\\n`;\nconst csvFilePath = './test.csv';\n\n// Create a dummy CSV file for the example\nfs.writeFileSync(csvFilePath, csvContent);\n\n(async () => {\n    let connection;\n    try {\n        // The 'csv:///' prefix activates the database-js-csv driver\n        connection = new Database(`csv://${csvFilePath}?headers=true&overwriteOnExecute=true`);\n        \n        let statement = await connection.prepareStatement(\"SELECT user_name, email FROM CSV WHERE user_name = ?\");\n        let rows = await statement.query('not_so_secret_user');\n        console.log('Query result for not_so_secret_user:', rows);\n\n        statement = await connection.prepareStatement(\"INSERT INTO CSV (user_name, email, role) VALUES (?, ?, ?)\");\n        await statement.execute('new_user', 'new@example.com', 'guest');\n        console.log('Inserted new user.');\n\n        // Query all data to see the inserted user\n        statement = await connection.prepareStatement(\"SELECT * FROM CSV\");\n        rows = await statement.query();\n        console.log('All data after insert:', rows);\n\n    } catch (error) {\n        console.error('Error:', error);\n    } finally {\n        if (connection) {\n            await connection.close();\n        }\n        // Clean up the dummy CSV file\n        fs.unlinkSync(csvFilePath);\n        console.log('Cleaned up test.csv');\n    }\n})();","lang":"javascript","description":"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."},"warnings":[{"fix":"Change `require('database-js2')` to `require('database-js')`.","message":"The example in the package's README uses `require('database-js2')`. This appears to be a typo or an outdated reference; the correct dependency for the core API is `database-js`. Always use `require('database-js')`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Include `require('database-js-csv');` at the beginning of your script, alongside `require('database-js');`.","message":"The `database-js-csv` package must be explicitly `require()`d to register its driver with the `database-js` core, even if you don't assign its exports to a variable. Without this, `database-js` will not recognize the `csv:///` connection string.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review `jl-sql-api`'s documentation and open issues for known limitations. Consider alternative CSV query libraries if complex SQL features are required.","message":"The underlying `jl-sql-api` package, which provides the SQL parsing, has not been actively maintained for several years (last update ~2 years ago). This may limit support for advanced SQL features or lead to unpatched bugs in the SQL parsing logic.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use absolute paths or carefully construct relative paths. Ensure special characters in paths are properly URL-encoded if not handled automatically by `database-js`.","message":"When specifying file paths in the connection string (e.g., `csv:///path/to/file.csv`), ensure they are correctly escaped and formatted for a URL. Relative paths might behave differently depending on the execution context and operating system.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Leverage connection string options like `?detectNumbers=true` or perform JavaScript type conversions after querying. Use `CAST()` functions within your SQL if supported by `jl-sql-api`.","message":"All data read from CSV files is initially treated as strings. While `jl-sql-api` has some type detection capabilities (e.g., `detectNumbers`, `detectDates`), explicit type casting within SQL queries or post-processing in JavaScript might be necessary for accurate data handling.","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":"Add `require('database-js-csv');` to your application's entry point to ensure the driver is initialized, typically after requiring `database-js` itself.","cause":"The `database-js-csv` driver was not loaded or registered with the core `database-js` library.","error":"Error: Driver not found for connection string: csv:///test.csv?headers=true&overwriteOnExecute=true"},{"fix":"Ensure `npm install database-js` is run and that you are importing `Connection` from `database-js` using `const { Connection } = require('database-js');` or `const Connection = require('database-js').Connection;`.","cause":"You are trying to destructure `Connection` from a module that doesn't export it, or the `database-js` package was not installed or imported correctly.","error":"TypeError: Cannot read properties of undefined (reading 'Connection')"},{"fix":"Verify the CSV file exists at the specified path, contains data, and has a header row if `headers=true` is used in the connection string. Check for correct delimiters or line endings.","cause":"The CSV file specified by the connection string either does not exist, is empty, or its format does not match the `headers=true` expectation.","error":"Error: CSV parsing error: Expected a header row but 'headers=true' was specified and the file is empty or malformed."}],"ecosystem":"npm"}