UNPKG

1.81 kBJavaScriptView Raw
1
2/*
3 * https://tools.ietf.org/html/rfc4180
4 *
5 * 6. Fields containing line breaks (CRLF), double quotes, and commas
6 should be enclosed in double-quotes. For example:
7
8 "aaa","b CRLF
9 bb","ccc" CRLF
10 zzz,yyy,xxx
11
12 7. If double-quotes are used to enclose fields, then a double-quote
13 appearing inside a field must be escaped by preceding it with
14 another double quote. For example:
15
16 "aaa","b""bb","ccc"
17 */
18
19
20!function(exports) {
21 exports.encode = encode
22 exports.decode = decode
23
24 var Item = require("../model").Item
25 , re = /"((?:""|[^"])*)"|[^",\n\r]+|\r?\n/g
26
27 function encode(obj, opts) {
28 var re = opts.re || /[",\r\n]/
29 , arr = Array.isArray(obj) ? obj : [ obj ]
30 , keys = opts.select ? opts.select.replace(/\[[^\]]+?\]/g, "").split(",") : Object.keys(arr[0])
31
32 arr = arr.map(function(obj) {
33 return keys.map(function(key) {
34 var value = Item.get(obj, key)
35 if (Array.isArray(value)) value = value.join(";")
36 return (
37 value == null ? opts.NULL :
38 re.test(value+="") ? '"' + value.replace(/"/g, '""') + '"' :
39 value
40 )
41 }).join(opts.delimiter)
42 })
43 if (opts.headers === "on") {
44 arr.unshift(keys.join(opts.delimiter))
45 }
46 return (opts.prefix || "") + arr.join(opts.br) + (opts.postfix || "")
47 }
48
49 function decode(str, opts) {
50 var match
51 , row = []
52 , head = row
53 , arr = []
54 , i = 0
55
56 if (opts && opts.head === false) {
57 arr.push(row = [])
58 head = null
59 }
60
61
62 for (; match = re.exec(str); ) {
63 if (match[0] === "\n" || match[0] === "\r\n") {
64 arr.push(row = head ? {} : [])
65 i = 0
66 } else {
67 row[
68 head && head !== row ?
69 head[i++] :
70 i++
71 ] = typeof match[1] === "string" ? match[1].replace(/""/g, '"') : match[0]
72 }
73 }
74 if (i==0) arr.length -= 1
75
76 return arr
77 }
78}(this)
79
80