【问题标题】:Un-TAR and un-GZip file stored as JavaScript BufferUn-TAR 和 un-GZip 文件存储为 JavaScript 缓冲区
【发布时间】:2019-12-04 05:33:01
【问题描述】:

我正在 Node.js/Express.js 上开发一个服务器脚本,它接收上传的包含多个文件的 .tar.gz 档案。该脚本必须解压缩存档中的 CSV 文件,解析它们并将其中一些存储在数据库中。无需在服务器上存储文件,只需处理它们即可。要上传文件,我使用 Multer 没有指定存储文件的位置,因此文件上传仅在 req.filesBuffer 中可用。

我的问题是,如何通过 untar 和 ungzip Buffer 来获取文件的内容? 如果我这样做:

const { unzipSync } = require('zlib');

const zipped = req.files[0];
const result = await unzipSync(zipped.buffer);
const str = result.toString('utf-8');

我得到的不是文件的内容,而是所有信息,包括文件名、一些元数据等作为字符串,这很难解析。有没有更好的办法?

【问题讨论】:

  • 为什么不使用实际的tar 然后从磁盘加载结果数据? (使用execspawn
  • 是的,或者更容易使用 Node 的 tar 模块,例如 npmjs.com/package/tar。我只是在想是否可以避免将上传保存到磁盘并从 Buffer 本身解压。
  • 如果你想解压一个tgz,你需要同时解压 untar。现在你只是解压缩。
  • 是的。但是如何在 JavaScript 中解压 Buffer 呢?我发现了很多模块,但没有这样的功能。它们主要处理文件系统中的文件或读取流。
  • 您确实链接到一个可以满足您需要的库,但您找不到具体的详细信息,因此:您可能想要ask for them to document how to do that on their issue tracker。这样一来,开源社区中的每个人都会受益。

标签: javascript node.js gzip tar multer


【解决方案1】:

我设法使用tar-streamstreamifier 库解压和解压缩缓冲区。

const tar = require('tar-stream');
const streamifier = require('streamifier');
const { unzipSync } = require('zlib');

const untar = ({ buffer }) => new Promise((resolve, reject) => {
  // Buffer is representation of .tar.gz file uploaded to Express.js server
  // using Multer middleware with MemoryStorage
  const textData = [];
  const extract = tar.extract();
  // Extract method accepts each tarred file as entry, separating header and stream of contents:
  extract.on('entry', (header, stream, next) => {
    const chunks = [];
    stream.on('data', (chunk) => {
      chunks.push(chunk);
    });
    stream.on('error', (err) => {
      reject(err);
    });
    stream.on('end', () => {
      // We concatenate chunks of the stream into string and push it to array, which holds contents of each file in .tar.gz:
      const text = Buffer.concat(chunks).toString('utf8');
      textData.push(text);
      next();
    });
    stream.resume();
  });
  extract.on('finish', () => {
    // We return array of tarred files's contents:
    resolve(textData);
  });
  // We unzip buffer and convert it to Readable Stream and then pass to tar-stream's extract method:
  streamifier.createReadStream(unzipSync(buffer)).pipe(extract);
});

使用这种方法,我设法避免在文件系统上存储任何临时文件,并专门处理内存中的所有文件内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2013-03-17
    • 2021-08-10
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多