4

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.

3
  • have you tried json-2-csv? Commented May 11, 2016 at 9:13
  • Just to be clear, is the delimiter actually a comma in your CSV? Commented May 11, 2016 at 9:13
  • yeah, comma delimited csvs. All the fields are enclosed in quotes. Commented May 12, 2016 at 12:38

1 Answer 1

4

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"
   ]
]
*/
Sign up to request clarification or add additional context in comments.

2 Comments

The output here is an array of JSON objects. I found that 'fast-csv' is another package that can handle such csvs. It supports output as String arrays, which was the format that I wanted.
@AthulJayson, if you remove column: true (or set it to false), csv also gives an array of string arrays. I updated my answer with the output without column: true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.