Node.js 在不解压的情况下读取 zip 文件 [英] Node.js read a file in a zip without unzipping it
本文介绍了Node.js 在不解压的情况下读取 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 zip 文件(实际上它是一个 epub 文件),我需要遍历其中的文件并读取它们,而无需将它们解压缩到磁盘.
I have a zip file (actually it's an epub file) I need to loop through the files in it and read them without unzipping them to the disk.
我尝试使用名为 JSZip
的 Node.js 库,但每个文件的内容都存储在内存中的 Buffer 中,每当我尝试将缓冲区内容解码为字符串时,返回的内容都是不可读的
I tried to use a Node.js library called JSZip
but the content of each file is stored in memory in Buffer and whenever I try to decode the buffer content to string the content returned is unreadable
这是我试过的代码:
const zip = new JSZip();
// read a zip file
fs.readFile(epubFile, function (err, data) {
if (err) throw err;
zip.loadAsync(data).then(function (zip) {
async.eachOf(zip.files, function (content, fileName, callback) {
if (fileName.match(/json/)) {
var buf = content._data.compressedContent;
console.log(fileName);
console.log((new Buffer(buf)).toString('utf-8'));
}
callback();
}, function (err) {
if (err) {
console.log(err);
}
});
});
});
推荐答案
由于 unzip 好像被放弃了,所以我用了 node-stream-zip 非常成功.
Since unzip seems to be abandoned, I used node-stream-zip with pretty good success.
npm install node-stream-zip
读取文件都是这样的:
const StreamZip = require('node-stream-zip');
const zip = new StreamZip({
file: 'archive.zip',
storeEntries: true
});
zip.on('ready', () => {
// Take a look at the files
console.log('Entries read: ' + zip.entriesCount);
for (const entry of Object.values(zip.entries())) {
const desc = entry.isDirectory ? 'directory' : `${entry.size} bytes`;
console.log(`Entry ${entry.name}: ${desc}`);
}
// Read a file in memory
let zipDotTxtContents = zip.entryDataSync('path/inside/zip.txt').toString('utf8');
console.log("The content of path/inside/zip.txt is: " + zipDotTxtContents);
// Do not forget to close the file once you're done
zip.close()
});
这篇关于Node.js 在不解压的情况下读取 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文