-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv-to-json.js
79 lines (67 loc) · 1.82 KB
/
csv-to-json.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const { fstat } = require('fs');
const stream = require('readable-stream');
const fs = require('fs');
const stringDecoder = require('string_decoder');
const split2 = require('split2');
const csv = require('csv');
const { Transform, Writable } = stream;
const byLine = () => new Transform({
transform(chunk, enc, callback) {
this._decoder = this._decoder || new stringDecoder.StringDecoder();
const lines = this._decoder.write(chunk).split('\n');
lines.forEach((line) => this.push(line));
callback();
}
});
const byColumn = () => new Transform({
objectMode: true,
transform(chunk, enc, callback) {
const columns = chunk.toString().split(':');
callback(null, columns);
}
});
const toJSON = () => new Transform({
objectMode: true,
transform(columns, enc, callback) {
if (!this.props) {
this.props = columns;
} else {
this.data = this.data || [];
const obj = columns.reduce((acc, value, index) => {
acc[this.props[index]] = value;
return acc;
}, {});
this.data.push(obj);
}
callback();
},
flush(callback) {
callback(null, this.data);
}
});
const log = () => new Writable({
objectMode: true,
write(chunk, enc, callback) {
console.log(chunk);
callback();
}
});
// fs.createReadStream('./csv/example.csv')
// .pipe(byLine())
// .pipe(byColumn())
// .pipe(toJSON())
// .pipe(log());
// fs.createReadStream('./csv/example.csv')
// .pipe(split2())
// .pipe(byColumn())
// .pipe(toJSON())
// .pipe(log());
// fs.createReadStream('./csv/example.csv')
// .pipe(csv.parse({ delimiter: ':' }))
// .pipe(log());
module.exports = {
log,
toJSON,
byColumn,
byLine,
}