我本以为我得到了数组中的所有CSV数据,但由于某种原因,我什么都没有得到.

有人能解释为什么a最后是空的吗?

const fs = require('fs');
const { parse } = require('csv-parse');

let a = [];

fs.createReadStream('./example.csv')
   .pipe(parse({ delimiter: ';', from_line: 2 }))
   .on('data', function (row) {
      a.push(row);
   })
   .on('end', function () {
      console.log('finished');
   })
   .on('error', function (error) {
      console.log(error.message);
   });

console.log(a);

推荐答案

您的aundefined,因为代码是异步执行的.执行console.log(a)后调用on()函数.

您可以在data事件或end事件中读取a的值:

fs.createReadStream('./example.csv')
   .pipe(parse({ delimiter: ';', from_line: 2 }))
   .on('data', function (row) {
      a.push(row);
      console.log(a) // <------- here
   })
   .on('end', function () {
      console.log('finished');
      console.log(a) // <------- here
   })
   .on('error', function (error) {
      console.log(error.message);
   });

一种解决方案可能是使用Promise

const readCSVData = async () => new Promise((resolve, reject) => {
let a = []
fs.createReadStream('./example.csv')
   .pipe(parse({ delimiter: ';', from_line: 2 }))
   .on('data', function (row) {
      a.push(row);
   })
   .on('end', function () {
      // return the a value 
      resolve(a) 
   })
   .on('error', function (error) {
      reject(error)
   });
})

// ..... 

const foo = async () => {
  const data = await readCSVData()
  console.log(data)
}

// or
readCSVData().then(a => console.log(a))

Javascript相关问答推荐

在JavaScript中使用setProperty方法试图修改css元素值时,我遇到错误

文件阅读器未读取一个文件

如何避免使用ajax在Vue 3合成API中重定向

在NextJS中使用计时器循环逐个打开手风琴项目?

创建1:1比例元素,以另一个元素为中心

D3多线图显示1线而不是3线

Vue:ref不会创建react 性属性

JS—删除对象数组中对象的子对象

如何避免页面第一次加载时由于CSS样式通过JavaScript更改而出现闪烁

Angular 中的类型错误上不存在获取属性

我怎么在JS里连续加2个骰子的和呢?

将核心模块导入另一个组件模块时存在多个主题

类构造函数忽略Reaction Native中的可选字段,但在浏览器中按预期工作

<;img>;标记无法呈现图像

FireBase云函数-函数外部的ENV变量

使用自动识别发出信号(&Q)

如何为仅有数据可用的点显示X轴标签?

OnClick更改Json数组JSX中的图像源

Node.js错误: node 不可单击或不是元素

P5.js中矩形内的圆弧