无法将数组推送到数组 - fast-csv,nodejs

Cannot push arrays to array - fast-csv, nodejs

我正在使用 fast-csv npm 包来解析传入的 csv 文件并捕获事件 data 并显示 row 绝对可以。我得到了我想要的。

What I've done:

fs.createReadStream(req.file.path)
  .pipe(csv.parse({ ignoreEmpty: true, trim: true }))
  .on("error", (error) => console.error(error))
  .on("data", (row) => console.log(row))
  .on("end", (rowCount) => console.log(rowCount));

What I got in data event:

['Data Entry Form']
['no','name','email','phone','address']
['1','John','john@gmail.com','09111111111','abc']
['2','Mary','mary@gmail.com','09111111111','abc']

What I need:

let data = [];

  fs.createReadStream(req.file.path)
    .pipe(csv.parse({ ignoreEmpty: true, trim: true }))
    .on("error", (error) => console.error(error))
    .on("data", (row) => data.push(_.compact(row)))
    .on("end", (rowCount) => console.log(rowCount));

  return res.status(201).send({
    status: "success",
    data,
  });

NOT OK:

data 是空的,我没有收到任何错误。

有什么建议吗?谢谢。

您应该仅在读取流结束时响应,如下所示:

let data = [];

fs.createReadStream(req.file.path)
    .pipe(csv.parse({ ignoreEmpty: true, trim: true }))
    .on("error", (error) => console.error(error))
    .on("data", (row) => data.push(_.compact(row)))
    .on("end", (rowCount) => {
        console.log(rowCount);
        res.status(201).send({
            status: "success",
            data,
        });
    });