Ale*_*Tok 3 javascript gzip tar node.js multer
我正在 Node.js/Express.js 上开发一个服务器脚本,用于接收上传的包含多个文件的 .tar.gz 存档。该脚本必须解压和解压存档中的 CSV 文件,解析它们并将其中一些存储在数据库中。不需要在服务器上存储文件,只需处理它们即可。为了上传文件,我使用 Multer 而不指定存储文件的位置,因此文件上传仅在req.filesas中可用Buffer。
我的问题是,如何解压 Buffer 来获取文件的内容?如果我做类似的事情:
const { unzipSync } = require('zlib');
const zipped = req.files[0];
const result = await unzipSync(zipped.buffer);
const str = result.toString('utf-8');
Run Code Online (Sandbox Code Playgroud)
我得到的不是文件的内容,而是所有信息,包括文件名、一些元数据等作为字符串,这很难解析。有没有更好的办法?
我设法使用tar-stream和Streamifier库解压和解压 Buffer。
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);
});
Run Code Online (Sandbox Code Playgroud)
使用这种方法,我设法避免在文件系统上存储任何临时文件,并专门处理内存中的所有文件内容。
| 归档时间: |
|
| 查看次数: |
3268 次 |
| 最近记录: |