csv-parser.ts
1 import * as fs from 'fs'; 2 import * as path from 'path'; 3 import csv from 'csv-parser'; 4 import { CSVRow, PlaceInfo } from './types'; 5 6 export class CSVParser { 7 private csvDirectory: string; 8 9 constructor(csvDirectory: string = './csv') { 10 this.csvDirectory = csvDirectory; 11 } 12 13 async getAllCSVFiles(): Promise<string[]> { 14 const files = await fs.promises.readdir(this.csvDirectory); 15 return files.filter(file => file.endsWith('.csv')); 16 } 17 18 async parseCSVFile(filename: string): Promise<PlaceInfo[]> { 19 const filePath = path.join(this.csvDirectory, filename); 20 const results: PlaceInfo[] = []; 21 22 return new Promise((resolve, reject) => { 23 fs.createReadStream(filePath) 24 .pipe(csv()) 25 .on('data', (row: CSVRow) => { 26 // Skip empty rows 27 if (!row['Название'] && !row['URL']) { 28 return; 29 } 30 31 results.push({ 32 name: row['Название'] || '', 33 note: row['Заметка'] || '', 34 url: row['URL'] || '', 35 tags: row['Теги'] || '', 36 comment: row['Комментарий'] || '' 37 }); 38 }) 39 .on('end', () => { 40 console.log(`Parsed ${results.length} places from ${filename}`); 41 resolve(results); 42 }) 43 .on('error', (error: Error) => { 44 reject(error); 45 }); 46 }); 47 } 48 49 async parseAllCSVFiles(): Promise<Map<string, PlaceInfo[]>> { 50 const files = await this.getAllCSVFiles(); 51 const results = new Map<string, PlaceInfo[]>(); 52 53 for (const file of files) { 54 try { 55 const places = await this.parseCSVFile(file); 56 results.set(file, places); 57 } catch (error) { 58 console.error(`Error parsing ${file}:`, error); 59 } 60 } 61 62 return results; 63 } 64 }