pipe道NodeJSstream到一个数组

我的用例是这样的:我正在阅读节点中的CSV文件,只有头。 我不想将读取stream的结果写入文件,而是一旦读取文件就将头部压入数组,所以我可以把这个数组放到后面去做。 或者,更好的是,在读取stream时,将其转换,然后将其发送到数组。 文件是一个人为的价值。 我被困在这一点,其中数据文件的当前输出是一个空的数组:

const fs = require('fs'); const parse = require('csv-parse'); const file = "my file path"; let dataFile = []; rs = fs.createReadStream(file); parser = parse({columns: true}, function(err, data){ return getHeaders(data) }) function getHeaders(file){ return file.map(function(header){ return dataFile.push(Object.keys(header)) }) } 

为了得到我需要的结果,我需要做什么? 我期待在数组中find标题作为最终结果。

好的,所以在你的代码中有一些令人困惑的事情,而且有一个错误:你实际上没有调用你的代码:)

首先是一个解决scheme,在parsing器之后添加这一行:

 rs.pipe(parser).on('end', function(){ console.log(dataFile); }); 

而魔术,dataFile不是空的。 您从磁盘stream式传输文件,将其传递给parsing器,然后在最后调用callback函数。

对于令人困惑的部分:

 parser = parse({columns: true}, function(err, data){ // You don't need to return anything from the callback, you give the impression that parser will be the result of getHeaders, it's not, it's a stream. return getHeaders(data) }) 

 function getHeaders(file){ // change map to each, with no return, map returns an array of the return of the callback, you return an array with the result of each push (wich is the index of the new object). return file.map(function(header){ return dataFile.push(Object.keys(header)) }) } 

最后:请select与结束线; 或不,但不是混合;)

你应该像这样结束:

 const fs = require('fs'); const parse = require('csv-parse'); const file = "./test.csv"; var dataFile = []; rs = fs.createReadStream(file); parser = parse({columns: true}, function(err, data){ getHeaders(data); }); rs.pipe(parser).on('end', function(){ console.log(dataFile); }); function getHeaders(file){ file.each(function(header){ dataFile.push(Object.keys(header)); }); }