2016-09-23 77 views
2

我遇到了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); 
+0

我只是重新阅读你的问题。告诉我们什么'async.series(请求)'做什么?但是一般来说,如果你期望在'async.series'上面的行上看到'console.log'请求,那么当然它会返回空的原因流不会像异步一样被阻塞。 – shriek

+0

这是async.js(https://caolan.github.io/async/docs.html#.series)库 – user1513388

+0

我明白了。所以这与你面临的问题无关。您可能需要创建一个承诺或传递一个回调,以完成填充'requests'然后'console.log'或对其执行'async.series'。 – shriek

回答

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

哇 - 谢谢。像魅力一样工作。我正在把头发撕掉,试图解决问题。 – user1513388

0

我只想用的流事件来连线事情:

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