Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

processing csv files with line breaks in fields - node.js

Im trying to process a csv file with line breaks (\n) inside the fields. Each field is enclosed in double quotes. Is there any node.js package that can handle this type of csv?

I tried parsing it with readline in node. It detects the lines as seperate records even though they are in the same field.

like image 787
Athul Jayson Avatar asked Sep 05 '25 03:09

Athul Jayson


1 Answers

csv can handle rows containing line breaks:

'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"
   ]
]
*/
like image 57
Shanoor Avatar answered Sep 07 '25 19:09

Shanoor