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:
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);
});