Node.js + 懒惰 : Iterate file lines

标签 node.js

我正在尝试延迟读取文件,但是我无法使用 each()。 我想读取一个文件的第一行,然后读取另一个文件的第一行,依此类推。

我正在尝试使用迭代器,但没有成功。 这是我的代码:

var Lazy = require('lazy.js');

var it = Lazy.readFile("log.txt")
        .lines()
        .getIterator();

while(it.moveNext()){
    console.log(it.current());
}

Lazy.readFile("log.txt").lines().size() 返回 0。

但是,这工作正常:

Lazy.readFile("log.txt")
        .lines()
        .each(function(line){
            console.log(line);
        });

最佳答案

这是 Lazy.js 的一部分,我承认我没有很好地解释它。让我复制 the current documentation for the getIterator method 中的片段这里:

This method is used when asynchronously iterating over sequences. Any type inheriting from Sequence must implement this method or it can't support asynchronous iteration.

Note that this method is not intended to be used directly by application code. Rather, it is intended as a means for implementors to potentially define custom sequence types that support either synchronous or asynchronous iteration.

您在这里遇到的问题是,Lazy.readFile 返回一个异步序列。因此 getIterator 将不起作用,因为 Iterator 类型仅公开同步接口(interface)。

自从你发布这个问题以来,我实际上已经更新了 Lazy.js;从 0.3.2 开始,在异步序列上调用 getIterator will throw an exception .

关于Node.js + 懒惰 : Iterate file lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927826/

相关文章:

node.js - Sequelize 或在 findAll() 中;

node.js - 如何在 Knex.js 中动态创建 where 条件?

node.js - 获取 Google Drive NodeJS 客户端的上传进度?

mysql - 多个控制字段在 Node.js 应用程序中不起作用

java - 使用 Nightwatch 测试 Node.js 项目时如何在 Travis CI 上运行 Selenium Server

javascript - nodejs multer diskstorage 在保存到磁盘后删除文件

javascript - 异步/等待类构造函数

node.js - Telegram Bot - NodeJs - 任务在循环中

node.js - PassportJS 和 Facebook Opengraph api 版本 2.0 错误

node.js - Mongoose - 尝试更新 MongoDB 中的对象,出现错误 : "object.save is not a function"