-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVFile.js
41 lines (36 loc) · 1.12 KB
/
CSVFile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import fs from 'fs';
import csv from '@fast-csv/format';
export class CSVFile {
static write(filestream, rows, options) {
return new Promise((res, rej) => {
csv.writeToStream(filestream, rows, options)
.on('error', err => rej(err))
.on('finish', () => res());
});
}
constructor(opts) {
this.headers = opts.headers;
this.path = opts.path;
this.writeOpts = { headers: this.headers, includeEndRowDelimiter: true };
}
create(rows) {
return CSVFile.write(fs.createWriteStream(this.path), rows, { ...this.writeOpts });
}
append(rows) {
return CSVFile.write(fs.createWriteStream(this.path, { flags: 'a' }), rows, {
...this.writeOpts,
// dont write the headers when appending
writeHeaders: false,
});
}
read() {
return new Promise((res, rej) => {
fs.readFile(this.path, (err, contents) => {
if (err) {
return rej(err);
}
return res(contents);
});
});
}
}