Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error parsing CSV file with NodeJS: "referenceerror: [first cell in table] is undefined

I’m so confused. I’m working on a function that will read the text in a CSV file and can’t get it to work. I’ve tried to break down the steps to find the bug and am still stuck. Right now, all I want is to be able to console.log the contents of the csv file.

I’m using NodeJS and just have the following code:

My code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const fs = require("fs")
const readline = require("readline");
const csvFilePath = require("./input/case-study-data.csv")

    fs.readFile(csvFilePath, function(err, data) {
console.log(data)
}

My table looks like this:

test1,test1,test1,
1,test,2,
rest,rest,test

The error I’m getting is this:

.csv:1
test1,test1,test1,
 ^

ReferenceError: test1 is not defined

>Solution :

The require function is primarily used to load modules (JavaScript files, .json, or .node files that can be parsed by Node.js). CSV files cannot be interpreted by Node.js. 

so, you should update your code:

const fs = require("fs")
const readline = require("readline");
const csvFilePath = "./input/case-study-data.csv";

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading