/
index.js
126 lines (108 loc) · 2.43 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
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
'use strict';
/**
* Module dependencies.
*/
var fs = require('fs');
var extend = require('extend-shallow');
/**
* Requires cache
*/
var requires = {};
/**
* Expose `parser`
*/
var parser = module.exports;
/**
* Parse the given `str` of CSV and callback `cb(err, json)`.
*
* @name .parse
* @param {String|Object} `str` The object or string to parse.
* @param {Object|Function} `options` or `cb` callback function.
* @param {Function} `cb` callback function.
* @api public
*/
parser.parse = function(str, options, cb) {
var csv = requires.csv || (requires.csv = require('parse-csv'));
if (typeof options === 'function') {
cb = options;
options = {};
}
var opts = extend({headers: {included: true}}, options);
try {
opts.jsonType = opts.jsonType || 'jsonDict';
cb(null, JSON.parse(csv.to(opts.csv, stripBOM(str), opts)));
} catch (err) {
cb(err);
return;
}
};
/**
* Parse the given `str` of CSV and return an object.
*
* @param {String|Object} `str` The object or string to parse.
* @return {Object}
* @api public
*/
parser.parseSync = function(str, options) {
var csv = requires.csv || (requires.csv = require('parse-csv'));
var opts = extend({headers: {included: true}}, options);
try {
opts.jsonType = opts.jsonType || 'jsonDict';
return JSON.parse(csv.to(opts.csv, stripBOM(str), opts));
} catch (err) {
return err;
}
};
/**
* CSV file support. Parse the given `str` of CSV and callback `cb(err, data)`.
*
* @param {String|Object} `str` The object or string to parse.
* @return {Object}
* @api public
*/
parser.parseFile = function(fp, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
var opts = extend({}, options);
try {
fs.readFile(fp, 'utf8', function(err, str) {
parser.parse(str, opts, cb);
});
} catch (err) {
cb(err);
return;
}
};
/**
* CSV file support. Parse a file at the given `fp`.
*
* ```js
* parser.parseFile('foo/bar/baz.csv');
* ```
*
* @param {String} `fp`
* @param {Object} `options` Options to pass to [parse-csv]
* @api public
*/
parser.parseFileSync = function(fp, options) {
try {
var str = fs.readFileSync(fp, 'utf8');
return parser.parseSync(str, options);
} catch (err) {
return err;
}
};
/**
* Strip byte-order marks
*
* @api private
*/
function stripBOM(str) {
if (str[0] === '\uFEFF') {
return str.substring(1);
} else {
return str;
}
}