[英]Un-TAR and un-GZip file stored as JavaScript Buffer
我正在 Node.js/Express.js 上開發一個服務器腳本,它接收帶有多個文件的上傳的 .tar.gz 檔案。 該腳本必須解壓和解壓存檔中的 CSV 文件,解析它們並將一些存儲在數據庫中。 無需在服務器上存儲文件,只需對其進行處理即可。 要上傳文件,我使用 Multer 而不指定存儲文件的位置,因此文件上傳僅在req.files
作為Buffer
可用。
我的問題是,如何解壓和解壓 Buffer 以獲取文件的內容? 如果我做這樣的事情:
const { unzipSync } = require('zlib');
const zipped = req.files[0];
const result = await unzipSync(zipped.buffer);
const str = result.toString('utf-8');
我得到的不是文件的內容,而是包括文件名、一些元數據等在內的所有信息作為字符串,這很難解析。 有沒有更好的辦法?
我設法使用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);
});
使用這種方法,我設法避免在文件系統上存儲任何臨時文件,而是專門處理內存中的所有文件內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.