简体   繁体   中英

NodeJS crashes after sometime of leading a csv file

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM