繁体   English   中英

将NodeJS流传输到数组

[英]Pipe NodeJS Stream to an Array

我的用例是这样的:我希望在Node中读取CSV文件,并且仅获取标头。 我不想将读取流的结果写入文件,而是在读取文件后将标头推入数组,因此我可以采用该数组并在以后对其进行处理。 或者,更好的是,获取流并在对其进行读取时对其进行转换,然后将其发送到数组。 文件是人为的值。 我被困在这一点上,数据文件的当前输出是一个空数组:

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

我需要做什么才能获得所需的结果? 我期望在数组中找到标头作为最终结果。

好的,所以您的代码中有些混乱的东西,还有一个错误:您实际上没有调用代码:)

首先,一个解决方案,在解析器之后添加以下行:

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

和魔术一样,dataFile不为空。 您从磁盘流式传输文件,将其传递到解析器,然后最后调用回调。

对于令人困惑的部分:

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

最后:请选择带有结束线的; 是否可以,但不能混合使用;)

您应该以以下内容结束:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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