-
Notifications
You must be signed in to change notification settings - Fork 30
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
Example how to use with node-fetch? #48
Comments
First, you need a way to convert a Node.js function readableStreamFromAsyncIterable(iterable) {
const it = iterable[Symbol.asyncIterator]();
return new ReadableStream({
async pull(controller) {
const { done, value } = await it.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
},
async cancel(reason) {
await it.throw(reason);
}
}, { highWaterMark: 0 });
}
// Usage:
const webStream = readableStreamFromAsyncIterable(nodeStream); In the future, this whole thing may be replaced by Second, you need to call this adapter on the stream returned by node-fetch import { Readable } from 'stream';
function getBodyAsWebStream() {
const body = this.body;
if (body instanceof Readable) {
return readableStreamFromAsyncIterable(body);
}
// If you also want to support a Buffer body:
if (body instanceof Buffer) {
return new ReadableStream({
start(controller) {
controller.enqueue(body);
controller.close();
}
})
}
return null;
}
fetch.Request.prototype.bodyAsWebStream = getBodyAsWebStream;
fetch.Response.prototype.bodyAsWebStream = getBodyAsWebStream; Note that monkey-patching a third-party library can lead to compatibility issues with future versions of that library, so I wouldn't recommend it.
From looking at their code, that wouldn't work. Their If you really want to monkey-patch, it seems that you'll need to patch both |
btw, there is an todo in node-fetch to remove the Buffer from the body and replacing it with a stream. so that this piece becomes unnecessary. // If you also want to support a Buffer body:
if (body instanceof Buffer) {
return new ReadableStream({
start(controller) {
controller.enqueue(body);
controller.close();
}
})
} |
thank you both, that helps a lot |
hi there, does anyone have an example how to use this polyfill combined with node-fetch?
the idea would be to hook up these libraries through a quick mapping..
unfortunately fetch.Body is not exported but perhaps the node-fetch authors would accept a PR to export it so it could be polyfilled..
or any other suggestions?
The text was updated successfully, but these errors were encountered: