UNPKG

943 BPlain TextView Raw
1import {CsvStringifier} from './csv-stringifiers/abstract';
2import {FileWriter} from './file-writer';
3
4const DEFAULT_INITIAL_APPEND_FLAG = false;
5
6export class CsvWriter<T> {
7 private readonly fileWriter: FileWriter;
8
9 constructor(private readonly csvStringifier: CsvStringifier<T>,
10 path: string,
11 encoding?: string,
12 private append = DEFAULT_INITIAL_APPEND_FLAG) {
13 this.fileWriter = new FileWriter(path, this.append, encoding);
14 }
15
16 async writeRecords(records: T[]): Promise<void> {
17 const recordsString = this.csvStringifier.stringifyRecords(records);
18 const writeString = this.headerString + recordsString;
19 await this.fileWriter.write(writeString);
20 this.append = true;
21 }
22
23 private get headerString(): string {
24 const headerString = !this.append && this.csvStringifier.getHeaderString();
25 return headerString || '';
26 }
27}