R0b0tn1k
R0b0tn1k

Reputation: 4306

Node.js: readfile reads just one line?

I'm trying to parse a CSV file line by line. However, when i output the contents of the file it shows just one line?

Here's the code:

fs.readFile('data.csv', 'utf8', function (err,data) {
    if (err) {
      return console.log(err);
    }

    console.log(data)
    var tbl = data.split('\n'); 
    console.log(tbl.length);
})

First console.log outputs just one line of data while tbl.length outputs 1.

Why is it reading just one line instead of the entire file?

EDIT: Something strange going on, if i do data.length i get 580218, which is much more than that one line i'm getting as output?

Upvotes: 1

Views: 1010

Answers (1)

R0b0tn1k
R0b0tn1k

Reputation: 4306

Wanted to give Jonathan the chance to answer so he could get the points.

So couple of issues going on here.

  1. Listing just one line from the CSV instead of the whole data. Turns out the JSON.strigify(string) did the trick. The extra lines or invalid characters may have caused it to output just one line, instead of the whole file.

  2. The array.length for the split operation returned 1 line. I noticed later that the entire csv file was the [0] element of the array. Apparently something to do with the new lines in the string. So i did stringily of the csv, and improved my split line a bit, and it worked.

Here's the modified code:

tbl = data.replace(/(\r\n|\n|\r)/gm,"|");
        tbl = tbl.split("|")
        console.log(tbl.length);

Voila!

Upvotes: 1

Related Questions