简体   繁体   English

将NodeJS流传输到数组

[英]Pipe NodeJS Stream to an Array

My use case is this: I am looking to read a CSV file in Node and get only the headers. 我的用例是这样的:我希望在Node中读取CSV文件,并且仅获取标头。 I don't want to write the results of a read stream to a file, rather push the headers to an array once the file is read, so I can take that array and do something to it later on. 我不想将读取流的结果写入文件,而是在读取文件后将标头推入数组,因此我可以采用该数组并在以后对其进行处理。 OR, better yet, take the stream and as it is being read, transform it, then send it to an array. 或者,更好的是,获取流并在对其进行读取时对其进行转换,然后将其发送到数组。 File is a contrived value. 文件是人为的值。 I am stuck at this point, where the current output of datafile is an empty array: 我被困在这一点上,数据文件的当前输出是一个空数组:

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

What do I need to do in order to get the results I need? 我需要做什么才能获得所需的结果? I am expecting the headers to be found in an array as the end result. 我期望在数组中找到标头作为最终结果。

Ok, so there is some confusing things in your code, and one mistake : you didn't actually call your code :) 好的,所以您的代码中有些混乱的东西,还有一个错误:您实际上没有调用代码:)

First, a solution, add this line, after parser : 首先,一个解决方案,在解析器之后添加以下行:

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

And magic, dataFile is not empty. 和魔术一样,dataFile不为空。 You stream the file from disk, pass it to the parser, then at the end, call a callback. 您从磁盘流式传输文件,将其传递到解析器,然后最后调用回调。

For the confusing parts : 对于令人困惑的部分:

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

And finaly : Please choose with ending line with ; 最后:请选择带有结束线的; or not, but not a mix ;) 是否可以,但不能混合使用;)

You should end with something like : 您应该以以下内容结束:

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