【问题标题】:Highland consume and toArray method together高地消费和toArray方法一起
【发布时间】:2017-12-27 02:04:33
【问题描述】:

大家好,节日快乐!

我正在尝试使用高地的 csv 行流。为了进行一些特殊处理并避免将标头传递给流,我调用了.consume(),然后我想要一个数组中的结果。问题是.toArray() 的回调永远不会被调用。我只是对此感到好奇,因为我已经将我的解决方案更改为.map().toArray(),但我仍然认为.consume() 将是一个更优雅的解决方案。 ;) 这是从 csv 文件读取并处理行的代码:

const fs = require('fs');
const _ = require('highland');

const dataStream = fs.createReadStream('file.csv', 'utf8');

_(dataStream)
  .split()
  .consume((err, row, push, next) => {
    console.log('consuming a row', row); // <-- this shows data

    if (err) {
      push(err);
      return next();
    }

    // This condition is needed as .consume() passes an extra {} at the end of the stream <-- donno what this happens!!
    if (typeof row !== 'string') {
      return next();
    }

    const cells = row.split(',');

    if (cells[0] === 'CODE') { // <-- header row
      const { columnNames, columnIndexes } = processHeader(cells)); // <-- not relevant, works okay
      return next();
    }

    console.log('processin content here', processRow(cells)); // <-- not relevant, works okay
    push(null, processRow(cells));
    return next();
  })
  .toArray(rows => console.log('ROWS: ', rows)); // <-- I don't get anything here

非常感谢!

【问题讨论】:

  • 我的回答可能并不完全正确,因为我确实再次查找了consume 的文档。 consume 似乎返回了一个新流,您可能必须关闭它才能真正调用 toArray。另请记住,该示例仅调用 push 和 next 而没有执行 return next()。话虽如此,如果结果数组很小,我更喜欢map.toArray。请记住,toArray 会将整个数据保存在内存中,这可能是您希望通过首先执行流来避免的事情。
  • 谢谢@k0pernikus,我会将登录信息用if () else () 包裹在.consume() 内,以避免return next() 并检查。是的,我想我可能最终会在.map() 中做任何我需要的事情,并使用 done() 关闭流。一次处理一行肯定会减少内存消耗。 :)
  • 为感兴趣的人提供更多信息:- 通过添加 if() { next () } else () { next() } 来避免 return next() 并没有什么不同。 - .consume() 正确地返回了一个新流,因为我可以处理它,在它之后链接一个 .map()

标签: javascript node.js highland.js


【解决方案1】:

consumetoArray 都使用流。您只能使用一次流。如果您尝试多次使用它,“流”将为空。

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 2012-02-05
    • 2014-01-18
    • 2017-02-15
    • 2021-07-28
    • 2020-04-07
    • 2020-10-09
    • 2016-10-16
    相关资源
    最近更新 更多