UNPKG

easy-cli-framework

Version:

A framework for building CLI applications that are robust and easy to maintain. Supports theming, configuration files, interactive prompts, and more.

90 lines (86 loc) 2.67 kB
'use strict'; var csv = require('csv-parser'); var ObjectsToCsv = require('objects-to-csv'); var fs = require('fs'); // @ts-ignore Untyped Module /** * A class to read and write CSV files. * * @class CsvFile * * @template TFileObject The type of object that the CSV file contains. */ class CsvFile { constructor(path) { /** * Read a CSV file and parse it into an array of objects. * * @throws {Error} If the file is not found or there is an error reading the file. * * @returns The parsed CSV file as an array of objects. * * @example * ```typescript * const csvFile = new CsvFile('data.csv'); * const data = await csvFile.read(); * ``` */ this.read = async () => new Promise(resolve => { let results = []; return fs .createReadStream(this.path) .pipe(csv()) .on('data', (data) => results.push(data)) .on('end', () => { resolve(results); }); }); /** * Write an array of objects to a CSV file overwriting the existing file. * * @param data The data to write to the CSV file. * * @throws {Error} If there is an error writing the file. * * @returns A promise that resolves when the file is written. * * @example * ```typescript * const csvFile = new CsvFile('data.csv'); * await csvFile.write([ * { name: 'Alice', age: 25 }, * { name: 'Bob', age: 30 }, * ]); * ``` */ this.write = async (data) => { const csv = new ObjectsToCsv(data); await csv.toDisk(this.path); }; /** * Append an array of objects to an existing CSV file. * * @param data The data to append to the CSV file. * * @throws {Error} If there is an error writing the file. * * @returns A promise that resolves when the file is written. * * @example * ```typescript * const csvFile = new CsvFile('data.csv'); * await csvFile.append([ * { name: 'Alice', age: 25 }, * { name: 'Bob', age: 30 }, * ]); * ``` */ this.append = async (data) => { const existingData = await this.read(); const csv = new ObjectsToCsv([...existingData, ...data]); await csv.toDisk(this.path); }; this.path = path; } } exports.CsvFile = CsvFile;