我正试着以流的形式发送图像...

  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);
    }
  );

也试过了

      const readableStream = new Readable();
      readableStream.read = () => {};
      for await (const chunk of ipfs.cat(cid)) {
        readableStream.push(chunk);
      }

我得到的信息是...

[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

当我判断标题时

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

推荐答案

您需要返回reply对象,因为您使用send函数管理响应.下面是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
    }

或者:

      reply.type("image/png")
      return readableStream

Node.js相关问答推荐

Nest Js - 在 multer 拦截器中如何设置最大文件上传大小并进行可选文件上传

Node.js中使用ffmpeg如何获取视频截图的位置?

为什么我不能将 id 发送到后端并通过 findByIdAndRemove() 删除项目?

无法使用 node 预签名 url 从 React 将图像文件上传到 s3

firebase/messaging 不提供名为 getToken 的导出

MongoDB Aggregate - 如何使用前一阶段的值作为下一阶段的字段名称?

在系统启动时启动本地 node 服务器

图像存储在后端文件夹中,但使用 multer 和 react.js 在前端找不到

如何使用来自前一阶段的另一个数组的聚合mongoose 在数组中添加字段

Pug - 包括带有include关键字的c代码

使用 mongoose 查找过go 7 天的注册用户总数

这到底是什么';拒绝未经授权';对我来说是什么意思?

如何undo撤消 Object.defineProperty 调用?

为当前目录提供服务的简单文件服务器

向 Stripe 提交付款请求时出现没有此类令牌错误

Node.js:socket.io 关闭客户端连接

使用 Monit 而不是基本的 Upstart 设置有什么好处?

为什么 Node.js 被命名为 Node.js?

Node.js 中的 PHP exit()/die() 类似功能是什么

Mongoose - 验证邮箱语法