1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
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 | , lines = str.match(re)
|
52 | , row = []
|
53 | , arr = [row]
|
54 |
|
55 | for (; match = re.exec(str); ) {
|
56 | if (match[0] === "\n" || match[0] === "\r\n") {
|
57 | arr.push(row = [])
|
58 | } else {
|
59 | row.push(typeof match[1] === "string" ? match[1].replace(/""/g, '"') : match[0])
|
60 | }
|
61 | }
|
62 |
|
63 | return arr
|
64 | }
|
65 | }(this)
|
66 |
|
67 |
|