Skip to content

Commit 181c512

Browse files
committed
Add new FileOutput type to stream.js
This takes a url and creates a `ReadableStream` that has two additional methods `url()` and `blob()` for easily working with remote URLs or base64 encoded data.
1 parent e7a1aac commit 181c512

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

lib/stream.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,61 @@ function createReadableStream({ url, fetch, options = {} }) {
9898
});
9999
}
100100

101+
function createFileOutput({ url, fetch }) {
102+
let type = "application/octet-stream";
103+
104+
class FileOutput extends ReadableStream {
105+
async blob() {
106+
const chunks = [];
107+
for await (const chunk of this) {
108+
chunks.push(chunk);
109+
}
110+
return new Blob(chunks, { type });
111+
}
112+
113+
url() {
114+
return new URL(url);
115+
}
116+
117+
toString() {
118+
return url;
119+
}
120+
}
121+
122+
return new FileOutput({
123+
async start(controller) {
124+
const response = await fetch(url);
125+
126+
if (!response.ok) {
127+
const text = await response.text();
128+
const request = new Request(url, init);
129+
controller.error(
130+
new ApiError(
131+
`Request to ${url} failed with status ${response.status}: ${text}`,
132+
request,
133+
response
134+
)
135+
);
136+
}
137+
138+
if (response.headers.get("Content-Type")) {
139+
type = response.headers.get("Content-Type");
140+
}
141+
142+
try {
143+
for await (const chunk of streamAsyncIterator(response.body)) {
144+
controller.enqueue(chunk);
145+
}
146+
controller.close();
147+
} catch (err) {
148+
controller.error(err);
149+
}
150+
},
151+
});
152+
}
153+
101154
module.exports = {
155+
createFileOutput,
102156
createReadableStream,
103157
ServerSentEvent,
104158
};

0 commit comments

Comments
 (0)