Created
January 27, 2021 20:40
-
-
Save SourceBoy/06629a7a53ac6bc81bf3892ab3288ac7 to your computer and use it in GitHub Desktop.
Translate ReadableStreamDefaultReader to Node.js stream.Readable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Translate ReadableStreamDefaultReader to Node.js stream.Readable | |
* @author SourceBoy | |
* @license MIT | |
*/ | |
async function pump(rs, _rs) { | |
const { done, value } = await rs.read(); | |
if (done) { | |
_rs.push(null); | |
return _rs; | |
} | |
const result = _rs.push(value); | |
if (!result) { | |
await new Promise((resolve) => { | |
_rs.once('read', resolve); | |
}); | |
} | |
return pump(rs, _rs); | |
} | |
fetch('/somewhere').then((response) => { | |
const rs = response.body.getReader(); | |
const _rs = new stream.Readable({ | |
read(size) { | |
this.emit('read', size); | |
} | |
}); | |
return pump(rs, _rs); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment