UNPKG

1.63 kBJavaScriptView Raw
1'use strict'
2
3// ===================================================================
4
5var parseCsv = require('csv-parser')
6var pumpify = require('pumpify')
7var through2 = require('through2')
8var stripBomStream = require('strip-bom-stream')
9
10// ===================================================================
11
12var noop = Function.prototype
13
14var hasOwn = Object.prototype.hasOwnProperty
15function parseDynamic (data) {
16 var name, value
17 for (name in data) {
18 if (hasOwn.call(data, name)) {
19 value = data[name].toLowerCase()
20 if (value === 'true') {
21 data[name] = true
22 } else if (value === 'false') {
23 data[name] = false
24 } else if (value !== '') {
25 value = +value
26 if (!isNaN(value)) {
27 data[name] = value
28 }
29 }
30 }
31 }
32}
33
34function removeUndefinedProps (obj) {
35 Object.keys(obj).forEach(function (key) {
36 if (obj[key] === undefined) {
37 delete obj[key]
38 }
39 })
40 return obj
41}
42
43function csv2json (opts) {
44 opts || (opts = {})
45
46 var process = opts.dynamicTyping
47 ? parseDynamic
48 : noop
49
50 return pumpify([
51 stripBomStream(),
52 parseCsv(removeUndefinedProps({
53 separator: opts.separator
54 })),
55 (function () {
56 var notFirst = false
57 var proxy = through2.obj(function (chunk, _, done) {
58 if (notFirst) {
59 this.push(',\n')
60 }
61 notFirst = true
62
63 process(chunk)
64
65 done(null, JSON.stringify(chunk))
66 }, function (done) {
67 this.push('\n]\n')
68 done()
69 })
70 proxy.push('[\n')
71
72 return proxy
73 })()
74 ])
75}
76exports = module.exports = csv2json