0

I've been working on a project that outputs xml upon reading a csv, I use the fs.createReadStream() method to read the csv file but after some time, the terminal just crashes.

And I get

C:\Users\username\Documents\Programming\Node Projects\DAE Parser\main.js:13
      row["Value"].includes("tri") ||
                   ^

TypeError: Cannot read property 'includes' of undefined

It doesn't read the whole file.

here's what i'm doing

fs.createReadStream("test.csv")
  .pipe(csv())
  .on("data", row => {
    if (
      row["Value"].includes("tri") ||
      row["Value"].includes("vt") ||
      row["Value"].includes("vx") ||
      row["Value"].includes("vn")
    ) {
      console.log(row)
    }
  })
Himanshu Sardana
  • 123
  • 2
  • 10

2 Answers2

1

Your row["Value"] is undefined, you can add a condition to check if it's falsy

fs.createReadStream("test.csv")
  .pipe(csv())
  .on("data", row => {
    if (row["Value"] && (
      row["Value"].includes("tri") ||
      row["Value"].includes("vt") ||
      row["Value"].includes("vx") ||
      row["Value"].includes("vn")
    )) {
      console.log(row)
    }
  })
Ditiz
  • 171
  • 2
  • 12
0

Your code is vulnerable in cases where:

  1. row is not an object
  2. row["Value"] does not exist or is not an array.

If you want to be completely safe against these in any particular row, then you can do this:

fs.createReadStream("test.csv")
  .pipe(csv())
  .on("data", row => {
    if (typeof row === "object") {
      let arr = row.Value;
      if (arr && Array.isArray(arr) && (
        arr.includes("tri") ||
        arr.includes("vt") ||
        arr.includes("vx") ||
        arr.includes("vn")
      )) {
        console.log(row);
      }
   }
})
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @himanshusardana - Did this answer your question? If so, you can indicate that to the community here by clicking the checkmark to the left of the answer. That will also earn you some reputation points here on stackoverflow for following the proper procedure. If this didn't answer your question, please comment about which part of your question you're still confused about. – jfriend00 Nov 25 '19 at 18:35