-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
55 lines (46 loc) · 1.14 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
'use strict';
const fs = require('fs'),
csv = require('fast-csv'),
request = require('request'),
isUrl = require('is-url'),
_ = require('lodash'),
isStream = require('is-stream');
/**
* Return a stream from a source.
* @param {String} src - File path, URL, or stream.
* @return {Object} - A stream
*/
function resolveSrc(src) {
if (isUrl(src)) {
return request(src);
}
if (isStream(src)) {
return src;
}
return fs.createReadStream(src);
}
function getCSV(src, opts, callback) {
const out = [];
let csvOpts;
if (typeof opts === 'function' && callback === undefined) {
callback = opts;
csvOpts = {};
}
csvOpts = _.defaults(opts, {headers: true});
return new Promise((resolve, reject)=>{
const readStream = resolveSrc(src)
.on('error', reject),
csvStream = csv(csvOpts)
.on('data', data => out.push(data))
.on('end', () => {
if (callback) callback(null, out);
resolve(out);
})
.on('error', (err) => {
if (callback) callback(err);
reject(err);
});
readStream.pipe(csvStream);
});
}
module.exports = getCSV;