Reputation: 5150
I'm trying to send an image as a stream...
const { Readable } = require("stream");
...
fastify.get(
"/v1/files/:cid",
async function (request: any, reply: any) {
const { cid }: { cid: string } = request.params;
const ipfs = create();
const readableStream = Readable({
async read() {
for await (const chunk of ipfs.cat(cid)) {
this.push(chunk);
}
this.push(null);
},
});
reply.type("image/png").send(readableStream);
}
);
also tried
const readableStream = new Readable();
readableStream.read = () => {};
for await (const chunk of ipfs.cat(cid)) {
readableStream.push(chunk);
}
The info I get is...
[17:31:38.006] INFO (44857): stream closed prematurely
reqId: "req-1"
res: {
"statusCode": 200
}
[17:31:38.006] INFO (44857): request completed
reqId: "req-1"
res: {
"statusCode": 200
}
responseTime: 28.260344982147217
and when I check the headers
Request Method: GET
Status Code: 200 OK
Remote Address: 0.0.0.0:4000
Referrer Policy: strict-origin-when-cross-origin
-------
Connection: keep-alive
content-length: 0
content-type: image/png
Date: Sun, 09 Oct 2022 16:44:07 GMT
Keep-Alive: timeout=72
vary: Origin
------
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
cp-extension-installed: Yes
Host: 0.0.0.0:4000
Pragma: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
Upvotes: 2
Views: 2617
Reputation: 12900
You need to return the reply
object because you manage the response using the send
function. Here the details from the docs.
async function (request: any, reply: any) {
const { cid }: { cid: string } = request.params;
const ipfs = create();
const readableStream = Readable({
async read() {
for await (const chunk of ipfs.cat(cid)) {
this.push(chunk);
}
this.push(null);
},
});
reply.type("image/png").send(readableStream);
return reply
}
Or:
reply.type("image/png")
return readableStream
Upvotes: 10