New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
readable and writable stream to duplex stream #2460
Comments
Try this: const duplexFromStreams = (rs, ws) => {
const ds = new class extends stream.Duplex{
#bufs = [];
#waiting = false;
allowHalfOpen = true;
constructor(){
super();
const push = buf => {
this.#bufs.push(buf);
if(this.#waiting){
this.push(this.#bufs.shift());
this.#waiting = false;
}
};
rs.on('data', buf => push(buf));
rs.on('end', () => push(null));
}
_read(){
while(this.#bufs.length !== 0)
if(!this.push(this.#bufs.shift()))
return;
this.#waiting = true;
}
write(buf, enc, cb){
return ws.write(buf, enc, cb);
}
}
ws.on('drain', () => ds.emit('drain'));
return ds;
}; |
Thanks for you code @Hakerh400 |
Simply add |
Yeah, that's what I thought at first, but |
Ok, I see what you mean. If you worry about the drain event, you can use |
The following code seems to handle
|
That works too. I tried to stream 2.6GB of data. but seems that your method is about ~2 times slower:
You can speed it up a lot by refactoring the method like this: _write(chunk, encoding, callback){
const ok = ws.write(chunk, encoding, () => {ok && callback()});
if(!ok) ws.once('drain', callback);
} |
Here is my final code: https://gist.github.com/FranckFreiburger/9af693b0432d7ee85d4e360e524551dc ...I have to admit that the result is quite similar to duplexer2 |
There has been no activity on this issue for 3 years and it may no longer be relevant. It will be closed 1 month after the last non-automated comment. |
There has been no activity on this issue and it is being closed. If you feel closing this issue is not the right thing to do, please leave a comment. |
Hello,
I try to write a simple function that converts a readable stream and a writable stream into a duplex stream:
I find it is very hard to obtain a satisfying result.
I know that some implementations exists (duplexify, duplexer2), but they don't work properly.
I'm wondering if you can give me some advice on how to do that and what pitfalls to avoid.
Thanks.
The text was updated successfully, but these errors were encountered: