-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (77 loc) · 2.04 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
var d3 = require("d3"),
byline = require('./lib/readline');
module.exports = function (opts, onLine, onClose) {
var count = 0;
if (typeof opts === "string") {
var filename = opts;
opts = {};
} else {
if (!opts.filename) {
console.log("Please pass a filename to streamCSV as { filename: 'myfile.csv' }");
return null;
}
var filename = opts.filename;
}
// you can pass specific fields to not convert to native type as comma-delimited
if (opts.dontguess && typeof opts.dontguess === "string") {
opts.dontguess = opts.dontguess.split(",");
}
var mode = opts.mode ? opts.mode.toLowerCase() : (/\.tsv$/.test(filename) ? "tsv" : "csv"),
header;
var rl = byline(filename);
rl.on('line', function(line) {
if (!opts.noheader && !header) {
header = line;
} else {
if (opts.noheader) {
datum = d3[mode].parseRows(line)[0];
} else {
datum = d3[mode].parse(header + "\n" + line)[0];
}
// don't record blank rows if asked
if (!opts.noheader && opts.sparse) {
for (var key in datum) if (datum.hasOwnProperty[key]) {
if (datum[key].replace(/\s+/, "") == "") {
delete datum[key];
}
}
}
// convert to native type unless asked not to
if (opts.dontguess !== true) {
for (var key in datum) if (datum.hasOwnProperty(key)) {
if (typeof opts.dontguess !== "object" || opts.dontguess.indexOf(key) == -1) {
datum[key] = guessType(datum[key]);
} else {
//console.log("Ignoring " + key);
}
}
}
onLine(datum, count);
count += 1;
}
});
rl.on("close", function() {
if (onClose) {
onClose();
}
});
}
// rudimentary type guessing. Can be improved upon
var reserved = {
"true": true,
"false": false,
"null": null
};
var guessType = module.guessType = function(str) {
if (typeof str === "undefined") {
return null;
}
if (/^-?\d+$/.test(str)) {
return parseInt(str, 10);
} else if (/^-?\d*\.\d+$/.test(str)) {
return parseFloat(str);
} else if (reserved.hasOwnProperty(str.toLowerCase())) {
return reserved[str.toLowerCase()];
}
return str;
}