代码之家  ›  专栏  ›  技术社区  ›  valerius21

将ReadStream值写入数组

  •  0
  • valerius21  · 技术社区  · 7 年前

    我正在尝试使用流和async,await关键字,使用fast csv lib同步读取csv。

    但是,我的函数似乎没有返回所需的输出。我的猜测是,我编写的函数中的函数/流所用的时间比node考虑生成我的console.log 用于输出数组长度的函数。

    我怎么退票 output 包含从csv流读取的所有值的数组?

    // CSV Processing
    async function readCsv(csvfilepath) {
        var output = []
        var stream = fs.ReadStream(csvfilepath)
        var parser = csv.fromStream(stream, {
            headers: true
        }).on("data", function (data) {
            parser.pause()
            t(data, output, function (err) {
                // TODO: handle error
                parser.resume()
            });
        }).on("end", function () {
            console.log(output) // outputs desired array with objects
            console.log(output.length) // length is 100
            // return output // does not work. output == [].
        });
    
    
        var t = (data, out, callback) => {
            out.push(data) // push the objects to that array
            callback()
        }
    
        console.log(output.length) // says length = 0
        return output // output is empty, should be filled with values exactly like in the 'end' event from the stream
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   valerius21    7 年前

    我用Promise对象解决了这个问题。resolve方法可以用于返回在流的“end”事件中处理的数据,同时仍然可以与async/await关键字一起使用。

    // CSV Processing
    function readCsv(csvfilepath) {
        var stream = fs.ReadStream(csvfilepath)
        return new Promise((resolve, reject) => {
            var output = []
            const parser = csv.fromStream(stream, {headers:true})
                .on('data', (data) => {
                    parser.pause();
                    c(data, output, (err) => {
                        if (err) reject(err)
                        parser.resume()
                    })
                })
                .on('end', () => {
                    resolve(output) // extraction/return point of the desired data
                })
            var c = (data, out, callback) => {
                out.push(data)
                callback()
            }
        })
    }