-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv-parser.js
374 lines (330 loc) · 11.2 KB
/
csv-parser.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
CSV-JS - A Comma-Separated Values parser for JS
Built to rfc4180 standard, with options for adjusting strictness:
- optional carriage returns for non-microsoft sources
- automatically type-cast numeric an boolean values
- relaxed mode which: ignores blank lines, ignores gargabe following quoted tokens, does not enforce a consistent record length
Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Author Greg Kindel (twitter @gkindel), 2014
*/
(function (global) {
'use strict';
/**
* @name CSV
* @namespace
*/
// implemented as a singleton because JS is single threaded
var CSV = {};
CSV.RELAXED = false;
CSV.IGNORE_RECORD_LENGTH = false;
CSV.IGNORE_QUOTES = false;
CSV.LINE_FEED_OK = true;
CSV.CARRIAGE_RETURN_OK = true;
CSV.DETECT_TYPES = true;
CSV.IGNORE_QUOTE_WHITESPACE = true;
CSV.DEBUG = false;
CSV.COLUMN_SEPARATOR = ",";
CSV.ERROR_EOF = "UNEXPECTED_END_OF_FILE";
CSV.ERROR_CHAR = "UNEXPECTED_CHARACTER";
CSV.ERROR_EOL = "UNEXPECTED_END_OF_RECORD";
CSV.WARN_SPACE = "UNEXPECTED_WHITESPACE"; // not per spec, but helps debugging
var QUOTE = "\"",
CR = "\r",
LF = "\n",
SPACE = " ",
TAB = "\t";
// states
var PRE_TOKEN = 0,
MID_TOKEN = 1,
POST_TOKEN = 2,
POST_RECORD = 4;
/**
* @name CSV.parse
* @function
* @description rfc4180 standard csv parse
* with options for strictness and data type conversion
* By default, will automatically type-cast numeric an boolean values.
* @param {String} str A CSV string
* @return {Array} An array records, each of which is an array of scalar values.
* @example
* // simple
* var rows = CSV.parse("one,two,three\nfour,five,six")
* // rows equals [["one","two","three"],["four","five","six"]]
* @example
* // Though not a jQuery plugin, it is recommended to use with the $.ajax pipe() method:
* $.get("csv.txt")
* .pipe( CSV.parse )
* .done( function(rows) {
* for( var i =0; i < rows.length; i++){
* console.log(rows[i])
* }
* });
* @see http://www.ietf.org/rfc/rfc4180.txt
*/
CSV.parse = function (str) {
var result = CSV.result = [];
CSV.offset = 0;
CSV.str = str;
CSV.record_begin();
CSV.debug("parse()", str);
var c;
while( 1 ){
// pull char
c = str[CSV.offset++];
CSV.debug("c", c);
// detect eof
if (c == null) {
if( CSV.escaped )
CSV.error(CSV.ERROR_EOF);
if( CSV.record ){
CSV.token_end();
CSV.record_end();
}
CSV.debug("...bail", c, CSV.state, CSV.record);
CSV.reset();
break;
}
if( CSV.record == null ){
// if relaxed mode, ignore blank lines
if( CSV.RELAXED && (c == LF || c == CR && str[CSV.offset + 1] == LF) ){
continue;
}
CSV.record_begin();
}
// pre-token: look for start of escape sequence
if (CSV.state == PRE_TOKEN) {
if ( (c === SPACE || c === TAB) && CSV.next_nonspace() == QUOTE ){
if( CSV.RELAXED || CSV.IGNORE_QUOTE_WHITESPACE ) {
continue;
}
else {
// not technically an error, but ambiguous and hard to debug otherwise
CSV.warn(CSV.WARN_SPACE);
}
}
if (c == QUOTE && ! CSV.IGNORE_QUOTES) {
CSV.debug("...escaped start", c);
CSV.escaped = true;
CSV.state = MID_TOKEN;
continue;
}
CSV.state = MID_TOKEN;
}
// mid-token and escaped, look for sequences and end quote
if (CSV.state == MID_TOKEN && CSV.escaped) {
if (c == QUOTE) {
if (str[CSV.offset] == QUOTE) {
CSV.debug("...escaped quote", c);
CSV.token += QUOTE;
CSV.offset++;
}
else {
CSV.debug("...escaped end", c);
CSV.escaped = false;
CSV.state = POST_TOKEN;
}
}
else {
CSV.token += c;
CSV.debug("...escaped add", c, CSV.token);
}
continue;
}
// fall-through: mid-token or post-token, not escaped
if (c == CR ) {
if( str[CSV.offset] == LF )
CSV.offset++;
else if( ! CSV.CARRIAGE_RETURN_OK )
CSV.error(CSV.ERROR_CHAR);
CSV.token_end();
CSV.record_end();
}
else if (c == LF) {
if( ! (CSV.LINE_FEED_OK || CSV.RELAXED) )
CSV.error(CSV.ERROR_CHAR);
CSV.token_end();
CSV.record_end();
}
else if (c == CSV.COLUMN_SEPARATOR) {
CSV.token_end();
}
else if( CSV.state == MID_TOKEN ){
CSV.token += c;
CSV.debug("...add", c, CSV.token);
}
else if ( c === SPACE || c === TAB) {
if (! CSV.IGNORE_QUOTE_WHITESPACE )
CSV.error(CSV.WARN_SPACE );
}
else if( ! CSV.RELAXED ){
CSV.error(CSV.ERROR_CHAR);
}
}
return result;
};
/**
* @name CSV.stream
* @function
* @description stream a CSV file
* @example
* node -e "c=require('CSV-JS');require('fs').createReadStream('csv.txt').pipe(c.stream()).pipe(c.stream.json()).pipe(process.stdout)"
*/
CSV.stream = function () {
var stream = require('stream');
var s = new stream.Transform({objectMode: true});
s.EOL = '\n';
s.prior = "";
s.emitter = function(s) {
return function(e) {
s.push(CSV.parse(e+s.EOL))
}
}(s);
s._transform = function(chunk, encoding, done) {
var lines = (this.prior == "") ?
chunk.toString().split(this.EOL) :
(this.prior + chunk.toString()).split(this.EOL);
this.prior = lines.pop();
lines.forEach(this.emitter);
done()
};
s._flush = function(done) {
if (this.prior != "") {
this.emitter(this.prior)
this.prior = ""
}
done()
};
return s
};
CSV.stream.json = function () {
var os = require('os');
var stream = require('stream');
var s = new streamTransform({objectMode: true});
s._transform = function(chunk, encoding, done) {
s.push(JSON.stringify(chunk.toString())+os.EOL);
done()
};
return s
};
CSV.reset = function () {
CSV.state = null;
CSV.token = null;
CSV.escaped = null;
CSV.record = null;
CSV.offset = null;
CSV.result = null;
CSV.str = null;
};
CSV.next_nonspace = function () {
var i = CSV.offset;
var c;
while( i < CSV.str.length ) {
c = CSV.str[i++];
if( !( c == SPACE || c === TAB ) ){
return c;
}
}
return null;
};
CSV.record_begin = function () {
CSV.escaped = false;
CSV.record = [];
CSV.token_begin();
CSV.debug("record_begin");
};
CSV.record_end = function () {
CSV.state = POST_RECORD;
if( ! (CSV.IGNORE_RECORD_LENGTH || CSV.RELAXED) && CSV.result.length > 0 && CSV.record.length != CSV.result[0].length ){
CSV.error(CSV.ERROR_EOL);
}
CSV.result.push(CSV.record);
CSV.debug("record end", CSV.record);
CSV.record = null;
};
CSV.resolve_type = function (token) {
if( token.match(/^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/) ){
token = parseFloat(token);
}
else if( token.match(/^(true|false)$/i) ){
token = Boolean( token.match(/true/i) );
}
else if(token === "undefined" ){
token = undefined;
}
else if(token === "null" ){
token = null;
}
return token;
};
CSV.token_begin = function () {
CSV.state = PRE_TOKEN;
// considered using array, but http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/
CSV.token = "";
};
CSV.token_end = function () {
if( CSV.DETECT_TYPES ) {
CSV.token = CSV.resolve_type(CSV.token);
}
CSV.record.push(CSV.token);
CSV.debug("token end", CSV.token);
CSV.token_begin();
};
CSV.debug = function (){
if( CSV.DEBUG )
console.log(arguments);
};
CSV.dump = function (msg) {
return [
msg , "at char", CSV.offset, ":",
CSV.str.substr(CSV.offset- 50, 50)
.replace(/\r/mg,"\\r")
.replace(/\n/mg,"\\n")
.replace(/\t/mg,"\\t")
].join(" ");
};
CSV.error = function (err){
var msg = CSV.dump(err);
CSV.reset();
throw msg;
};
CSV.warn = function (err){
var msg = CSV.dump(err);
try {
console.warn( msg );
return;
} catch (e) {}
try {
console.log( msg );
} catch (e) {}
};
// Node, PhantomJS, etc
// eg. var CSV = require("CSV"); CSV.parse(...);
if ( typeof module != 'undefined' && module.exports) {
module.exports = CSV;
}
// CommonJS http://wiki.commonjs.org/wiki/Modules
// eg. var CSV = require("CSV").CSV; CSV.parse(...);
else if (typeof exports != 'undefined' ) {
exports.CSV = CSV;
}
// AMD https://github.com/amdjs/amdjs-api/wiki/AMD
// eg. require(['./csv.js'], function (CSV) { CSV.parse(...); } );
else if (typeof define == 'function' && typeof define.amd == 'object'){
define([], function () {
return CSV;
});
}
// standard js global
// eg. CSV.parse(...);
else if( global ){
global.CSV = CSV;
}
})(this);