CSVファイルパースと検索条件
const fs = require('fs'); const parse = require('csv-parser/lib/sync'); class CsvReader { constructor(filePath, hasHeader = true) { this.filePath = filePath; this.hasHeader = hasHeader; } readCsv() { try { const csvData = fs.readFileSync(this.filePath, 'utf8'); const rows = parse(csvData, { skip_empty_lines: true, skip_lines_with_empty_values: true, ...(this.hasHeader && { headers: true }), // Include headers if hasHeader is true }); return rows; } catch (error) { throw new Error(`Error reading CSV file: ${error.message}`); } } searchByColumnValues(conditions) { const data = this.readCsv(); return data.filter((row) => { return conditions.every((condition) => { const [column, value] = Object.entries(condition)[0]; return row[column] === value; }); }); } } // Usage example const csvReader = new CsvReader('path/to/your/csv/file.csv', true); // Set hasHeader to true const searchConditions = [ { "Product": "Carrot" }, { "Category": "Vegetables" } ]; const searchResults = csvReader.searchByColumnValues(searchConditions); console.log('Matching rows:', searchResults);