处理字段中包含换行符的csv文件 - node.js

时间:2016-05-11 09:05:33

标签: javascript arrays node.js parsing npm

我试图在字段内处理带换行符(\ n)的csv文件。每个字段都用双引号括起来。是否有任何node.js包可以处理这种类型的csv?

我尝试用节点中的readline解析它。它将行检测为单独的记录,即使它们位于同一个字段中。

1 个答案:

答案 0 :(得分:2)

csv可以处理包含换行符的行:

'use strict'

let csv = require('csv');

let str = `id;name;desc
"1";"name1";"desc
on multiple
line"
"2";"name2";"desc2"`;

csv.parse(str,
    {
        delimiter: ';', // default is ,
        columns: true,  // if the first of the csv line is headers
    },
    (err, data) => {
        if (err) console.log(err);
        console.log(JSON.stringify(data, null, 3));
    });

/* output:
[
   {
      "id": "1",
      "name": "name1",
      "desc": "desc\non multiple\nline"
   },
   {
      "id": "2",
      "name": "name2",
      "desc": "desc2"
   }
]
*/

/* without column: true
[
   [
      "id",
      "name",
      "desc"
   ],
   [
      "1",
      "name1",
      "desc\non multiple\nline"
   ],
   [
      "2",
      "name2",
      "desc2"
   ]
]
*/