如何重置Node.js流? [英] How to reset nodejs stream?

查看:102
本文介绍了如何重置Node.js流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重置Node.js流? 如何在nodejs中再次读取流? 预先感谢!

How to reset nodejs stream? How to read stream again in nodejs? Thanks in advance!

var fs = require('fs');
var lineReader = require('line-reader');

// proxy.txt = only 3 lines

var readStream = fs.createReadStream('proxy.txt');
lineReader.open(readStream, function (err, reader) {
    for(var i=0; i<6; i++) {
        reader.nextLine(function(err, line) {
            if(err) {
                readStream.reset(); // ???
            } else {
                console.log(line);
            }
        });
    }
});

推荐答案

有两种方法可以解决您的问题,因为有人评论说,您可以将所有内容都包装到函数中而不是进行重置-只需重新读取文件即可.

There are two ways of solving your problem, as someone commented before you could simply wrap all that in a function and instead of resetting - simply read the file again.

例如,Ofc不适用于HTTP请求,因此反之,如果您考虑到更大的内存使用量,则可以简单地累积数据.

Ofc this won't work well with HTTP requests for example so the other way, provided that you do take a much bigger memory usage into account, you can simply accumulate your data.

您需要实现某种可重绕流"-这意味着您实际上需要实现一个Transform流,该Transform流将保留所有缓冲区的列表并将其写入到管道上的管道流中.倒带方法.

What you'd need is to implement some sort of "rewindable stream" - this means that you'd essentially need to implement a Transform stream that would keep a list of all the buffers and write them to a piped stream on a rewind method.

在这里查看流的节点API ,方法应该看起来有些类似像这样.

Take a look at the node API for streams here, the methods should look somewhat like this.

class Rewindable extends Transform {

  constructor() {
    super();
    this.accumulator = [];
  }

  _transform(buf, enc, cb) { 
    this.accumulator.push(buf);
    callback()
  }

  rewind() {
    var stream = new PassThrough();
    this.accumulator.forEach((chunk) => stream.write(chunk))
    return stream;
  }

您将这样使用:

var readStream = fs.createReadStream('proxy.txt');
var rewindableStream = readStream.pipe(new Rewindable());

(...).on("whenerver-you-want-to-reset", () => {
    var rewound = rewindablesteram.rewind();
    /// and do whatever you like with your stream.
});

实际上,我想将其添加到我的 scramjet 中. :)

Actually I think I'll add this to my scramjet. :)

我在 rereadable-stream npm软件包中发布了以下逻辑.此处描述的流的结果是,您现在可以控制缓冲区长度并摆脱读取的数据.

I released the logic below in rereadable-stream npm package. The upshot over the stream depicted here is that you can now control the buffer length and get rid of the read data.

同时,您可以保留一个由count个项目组成的窗口,并向后拖尾一些块.

At the same time you can keep a window of count items and tail a number of chunks backwards.

这篇关于如何重置Node.js流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆