使用节点从内存缓冲区(非磁盘)创建 tarball 并将结果存储在内存中

joh*_*01s 6 buffer file tar in-memory node.js

假设我有两个缓冲区:

const bufferFile1 = Buffer.from('Hello World!', 'utf-8')
const bufferFile2 = Buffer.from('Hello Again World!', 'utf-8')
Run Code Online (Sandbox Code Playgroud)

我如何创建 tarball 文件缓冲区/流/blob(不写入磁盘),其中上面的两个缓冲区应作为 tarball 中的两个文件存储。我希望(能够)通过管道传输 tarball 作为对请求的响应。

我研究过使用tar包。但这个解决方案需要路径而不是内存流/缓冲区。

这有可能实现吗?

PS:我对内存文件处理的经验很少。


整个项目是创建一个api端点

  • 接受参数作为 POST 正文或 url 查询参数。
  • 创建一组内存文件,其内容基于输入
  • 根据这些文件创建一个 tar.gz 文件
  • 使用 GridFS 将 tar.gz 文件存储在 mongodb 中

我真的没有地方临时存储文件(无服务器环境),这就是为什么我希望解决方案完全在内存中。

Icy*_*cle 2

我能够让它与archiver和 axios 一起工作。

archivertar-stream是和的包装zip-stream。所以这可以通过类似的方式来实现tar-stream,但我没有让它工作。

如果 archive.read() 给null你应该确保

  1. archive.read() 位于archive.on("finish",...
  2. archive.on("finish",...之前被调用archive.finalize()

这是我的完整代码片段:


const axios = require("axios");
const archiver = require("archiver");

const archive = archiver("tar", { gzip: false, store: false });

// data is a string representation of the text.
archive.append(data, { name: "main.txt" });


archive.on("finish", () => {
  const blob = new Blob([archive.read()], { type: "application/x-tar" });
  const formData = new FormData();
  // FormData seems to only accept blob
  formData.append("file", blob);
  axios
    .post(url, formData, {
      // remove this if your file is not in a binary format
      responseType: 'arraybuffer'
    })
    .then((response) => {
      console.log(response.data); // the response and data 
    })
    .catch((error) => {
      console.error(error);
    });
});

// doing this after registering the events or else it will the data might not be present
archive.finalize();

Run Code Online (Sandbox Code Playgroud)