gpt4 book ai didi

node.js - EOF 后出现错误 : stream. Push()

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:42 26 4
gpt4 key购买 nike

使用 Node 流

此代码从index.js 读取并写入indexCopy.js - 一种文件副本。目标文件已创建,但在执行过程中抛出异常:

node index.js
events.js:183
throw er; // Unhandled 'error' event
^

Error: stream.push() after EOF
at readableAddChunk (_stream_readable.js:240:30)
at MyStream.Readable.push (_stream_readable.js:208:10)
at ReadStream.f.on (C:\Node\index.js:16:28)
at emitOne (events.js:116:13)
at ReadStream.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at ReadStream.Readable.push (_stream_readable.js:208:10)
at fs.read (fs.js:2042:12)
at FSReqWrap.wrapper [as oncomplete] (fs.js:658:17)

C:\Node>

这是代码:

var util = require('util');
var stream = require('stream');
var fs = require('fs');


var MyStream = function(){
stream.Readable.call(this)
}

util.inherits(MyStream,stream.Readable);


MyStream.prototype._read = function(d){

f = fs.createReadStream("index.js");
f.on('data',(d)=>{this.push(d)});
f.on('end',()=>{this.push(null)}); //when file finished need to close stream

}


var f = fs.createWriteStream("indexCopy.js")

var myStream = new MyStream()
myStream.pipe(f);

我尝试在“data”事件中调用 this.push(null),在这种情况下,甚至不会创建目标文件,并且代码会失败并出现异常。

我意识到使用 Pipe() 函数应该更容易复制文件 - 我只是在试验/学习。我的方法有什么问题吗?

最佳答案

您不希望 _read 方法中包含 f = fs.createReadStream("index.js") 行 -- _read被重复调用,因此您正在创建多个读取流。将其放入您的构造函数中。

function MyStream () {
stream.Readable.call(this);
this.source = fs.createReadStream("index.js");
this.haveBound = false;
}
MyStream.prototype._read = function () {
if (this.haveBound) return; // Don't bind to events repeatedly
this.haveBound = true;
this.source.on("data", d => this.push(d));
this.source.on("end", () => this.push(null));
};

不过这很尴尬。流意味着管道'ed。

关于node.js - EOF 后出现错误 : stream. Push(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com