短视频源码实现流式传输,降低处理大文件时对内存的占用

短视频源码实现流式传输,降低处理大文件时对内存的占用
其实当使用 Node.js 向短视频源码客户端返回大文件时,我们最好使用流的形式来返回文件流,这样能避免处理大文件时,占用过多的内存。具体实现方式如下所示:

const fs = require("fs");
const zlib = require("zlib");
const http = require("http");

http
  .createServer((req, res) => {
    res.writeHead(200, {
      "Content-Type": "text/plain;charset=utf-8",
      "Content-Encoding": "gzip",
    });
    fs.createReadStream(__dirname + "/big-file.txt")
      .setEncoding("utf-8")
      .pipe(zlib.createGzip())
      .pipe(res);
  })
  .listen(3000, () => {
    console.log("app starting at port 3000");
  });

 

当使用流的形式来返回文件数据时,HTTP 响应头 Transfer-Encoding 字段的值为 chunked,表示数据以一系列分块的形式进行发送。

Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/plain;charset=utf-8
Date: Sun, 06 Jun 2021 01:02:09 GMT
Transfer-Encoding: chunked

 

以上就是短视频源码实现流式传输,降低处理大文件时对内存的占用, 更多内容欢迎关注之后的文章

 

posted @ 2024-02-03 09:26  云豹科技-苏凌霄  阅读(20)  评论(0编辑  收藏  举报