0

我是 js 新手,并尝试使用 node.js 在后端解析 CSV。

我有一个状态数组,我想在其中存储 CSV 列的数据。这是我使用 fast-csv 编写的一个非常简单的代码。但是每当我运行代码时,我都会得到一个空数组 [] 。我尝试使用 papaparse 做同样的事情并得到相同的结果。

const csv = require('fast-csv')
const file = fs.createReadStream('main.csv');
var states = []
file
    .pipe(csv.parse({ headers: false }))
    .on('data', row => states.push(row[2]))
console.log(states)

但是,每当我通过控制台登录时, .on('end') 块都会记录这些值。

const csv = require('fast-csv')
const file = fs.createReadStream('main.csv');
var states = []
file
    .pipe(csv.parse({ headers: false }))
    .on('data', row => states.push(row[2]))
    .on('end', () => console.log(states) // This works
console.log(states) // This doesn't

我认为这是由于解析器异步工作。我试图解决承诺并使用 async/await 方法,但我无法在全局范围内使用已解析的内容。

希望对此有所帮助。

4

1 回答 1

0

你是对的,解析器是异步工作的。因此,它开始解析并对事件使用回调(在您的情况下为“数据”、“结束”)。但是解析器之后的代码将在解析器开始工作后立即执行。因此,您对解析数据的所有操作都应在“结束”事件回调中完成。

// function to start parser
const startParsing = (res) => {
  const csv = require('fast-csv')
  const file = fs.createReadStream('main.csv');
  // you may use const cos it's type won't be changed
  const states = []
  file
    .pipe(csv.parse({ headers: false }))
    .on('data', row => states.push(row[2]))
    // execute function after parsing.
    .on('end', () => outputData(states, res));
};

const outputData = (states, res) => {
  // your next actions here
  console.log(states);
  // for example, res.send(states) or anything to complete server response if it's accessible
  res.send(states);  
};

// then, in any place you need use this startParsing function, for example
server.get('/parser', (req, res) => {
  startParsing(res);
});

于 2021-06-24T13:28:27.053 回答