“Error parsing CSV file with NodeJS: ‘referenceerror: [first cell in table] is undefined.”

huangapple go评论64阅读模式
英文:

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:

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
英文:

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

答案1

得分: 1

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

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

huangapple
  • 本文由 发表于 2023年6月9日 13:05:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437369.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定