Node.js读取zip中的文件而不解压缩它
Node.js read a file in a zip without unzipping it
我有一个zip文件(实际上是一个epub文件(,我需要循环浏览其中的文件并读取它们,而无需将它们解压缩到磁盘。
我尝试使用一个名为JSZip
的Node.js库,但每个文件的内容都存储在Buffer中的内存中,每当我尝试解码缓冲区内容以字符串时,返回的内容都是不可读的
这是我尝试过的代码:
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似乎被放弃了,我使用了节点流zip,并取得了相当好的成功。
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()
});
npm install unzip
https://www.npmjs.com/package/unzip
fs.createReadStream('path/to/archive.zip')
.pipe(unzip.Parse())
.on('entry', function (entry) {
var fileName = entry.path;
var type = entry.type; // 'Directory' or 'File'
var size = entry.size;
if (fileName === "this IS the file I'm looking for") {
entry.pipe(fs.createWriteStream('output/path'));
} else {
entry.autodrain();
}
});
相关文章:
- grunt上的压缩文件夹不起作用
- 用有限的字符集压缩字符串,然后在JS中解压缩
- nodegzip将文件解压缩到变量中
- 在树枝模板上从数据库中解压缩HTML字符串
- express js 4.4.1中的压缩文件(gzip)
- 临时解压缩文件以在浏览器中查看内容
- 使用.htaccess压缩文件时出现500错误
- 如何解压缩NodeJS请求's模块gzip响应体
- 在C#中压缩字符串,然后在JavaScript中解压缩
- 如何在JS Uglify2中尽可能多地压缩文件
- 如何在javascript/jquery中解压缩bzip2数据
- 使用拼音间隙解压缩文件
- 大 JSON 文件 - 如何在服务器中压缩并在客户端解压缩
- 使用Javascript如何在移动设备上从使用PhoneGap构建的应用程序中解压缩文件
- 用JavaScript解压缩文件
- 如何解压缩xxx.js.tar文件
- 如何解压缩gzip文件
- 如何从JavaScript文件中正确解压缩编码为JSON的PHP数组中的数据
- 如何用javascript解压缩gzip文件
- 在Angularjs客户端解压缩一个包含文件的文件夹作为内容