【问题标题】:streaming from large files and creating an array从大文件流式传输并创建数组
【发布时间】:2016-09-23 14:21:53
【问题描述】:

我遇到了 highland.js 的问题。我需要从我的流数据中创建一个函数数组,但不能让它工作。这是我的代码,但requests 始终为空。

var requests = [];           
_(fs.createReadStream("small.txt", { encoding: 'utf8' }))
        .splitBy('-----BEGIN-----\n')
        .splitBy('\n-----END-----\n')
        .filter(chunk => chunk !== '')
        .each(function (x) {

            requests.push(function (next) {
                Helpers.Authenticate()
                    .then(function (response1) {
                        return Helpers.Retrieve();
                    })
                    .then(function (response2) {
                        return Helpers.Retrieve();
                    })
                    .then(function () {
                        next();
                    });
            });

        });
        console.log(requests)
        async.series(requests);

【问题讨论】:

  • 我刚刚重新阅读了您的问题。介意告诉我们async.series(requests) 做了什么吗?但总的来说,如果您希望console.log 上面的行看到async.series 上的请求,那么它当然会返回空的,因为流不会像异步一样阻塞。
  • 我明白了。因此,这与您面临的问题无关。您可能需要为流创建一个承诺或传递一个回调以完成填充requests,然后将console.log 输出或对其执行async.series
  • .each 是一个 jQuery 函数。如果您使用 forEach,则不使用 X 参数。
  • @manuerumx 它也是highlandjs 中的一个函数。

标签: javascript node.js highland.js


【解决方案1】:

请阅读highland's 文档。尝试将.done 添加到您的信息流中,然后将console.log 添加到requests 之外。

_(fs.createReadStream("small.txt", { encoding: 'utf8' }))
    .splitBy('-----BEGIN-----\n')
    .splitBy('\n-----END-----\n')
    .filter(chunk => chunk !== '')
    .each(function (x) {

        requests.push(function (next) {
            Helpers.Authenticate()
                .then(function (response1) {
                    return Helpers.Retrieve();
                })
                .then(function (response2) {
                    return Helpers.Retrieve();
                })
                .then(function () {
                    next();
                });
        });

    }).done(function(){
      console.log(requests);
    });

【讨论】:

  • 哇-谢谢。像魅力一样工作。我正在努力解决问题。
【解决方案2】:

我只会使用流事件来连接:

var stream = fs.createReadStream('small.txt', {encoding: "utf8"});

stream.on('data', (line) => {
    var lineStr = line.toString(); //Buffer to String
    /* You code here */
})

stream.on('close', (line) => {
    console.log(request);
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2018-04-02
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多