[英]Creating a zip file from a JSON object using adm-zip
I'm trying to create a .zip
file from a JSON object in Node.js. 我正在尝试从Node.js中的JSON对象创建一个
.zip
文件。 I'm using adm-zip to do that however I'm unable to make it work with this code: 我正在使用adm-zip来执行此操作,但是无法通过以下代码使其起作用:
var admZip = require('adm-zip');
var zip = new admZip();
zip.addFile(Date.now() + '.json', new Buffer(JSON.stringify(jsonObject));
var willSendthis = zip.toBuffer();
fs.writeFileSync('./example.zip', willSendthis);
This code creates example.zip
but I'm not able to extract it, I tried with a .zip
extractor but also with this code: 这段代码创建了
example.zip
但我无法提取它,我尝试使用.zip
提取器,但也尝试使用此代码:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.data.toString('utf8'));
});
It returns Cannot read property 'toString' of undefined
at the line with console.log
. 它在
console.log
的行中返回Cannot read property 'toString' of undefined
。
I could use zip.writeZip()
for this example but I'm sending the .zip
file to Amazon S3 thus I need to use the method .toBuffer()
to do something like this after using adm-zip
: 在本示例中,我可以使用
zip.writeZip()
,但是我将.zip
文件发送到Amazon S3,因此在使用adm-zip
之后,我需要使用.toBuffer()
方法执行以下操作:
var params = {Key: 'example.zip', Body: zip.toBuffer()};
s3bucket.upload(params, function(err, data) {...});
I don't see what is wrong, am I using the package correctly? 我看不出有什么问题,我是否正确使用了包装?
Try use zipEntry.getData().toString('utf8')
instead zipEntry.data.toString('utf8')
: 尝试使用
zipEntry.getData().toString('utf8')
代替zipEntry.data.toString('utf8')
:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.getData().toString('utf8'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.