我尝试使用aws-sdk从AWS S3下载zip文件。我的代码下载文件,但它已损坏。我无法用7zip程序和zip命令解压缩它。也许有一些我错过的编码。
这是我的代码:
require('dotenv').config();
const AWS = require('aws-sdk');
const fs = require('fs');
const commandLineArgs = require('command-line-args');
const options = commandLineArgs([
{name: 'filename', alias: 'f', type: String},
]);
gulp.task('zipFromS3', function() {
var AWS = require('aws-sdk');
var fs = require('fs');
AWS.config.update({accessKeyId: process.env.AWS_ACCESS_ID,secretAccessKey: process.env.AWS_ACCESS_SECRET});
var s3bucket = new AWS.S3({params:{Bucket: env.aws.access_backups.bucket}});
return new Promise(function(resolve,reject){
if(options.filename == null || typeof options.filename == 'undefined'){
return reject();
}
let filename = options.filename; //'2017-04-06.zip'
var file = fs.createWriteStream(env.server.downloads + '/'+filename);
var params = {
Key: filename,
Bucket: env.aws.access_backups.bucket
};
s3bucket.getObject(params, function(err, data){
if (err) {reject();}
}).createReadStream()
.on('error', function(err){
console.log(err);
reject();
})
.on('end', function (chunk){
resolve();
}).pipe(file);
});
});
我使用此脚本从s3下载一些.txt文件,这很有效。如果我去我的桶并直接从aws网站下载我的zip文件,它也可以正常工作。
压缩文件也是gulp创建的。这是创建zip文件的代码(在发送到AWS之前,此zip文件可以正确解压缩。)
const zip = require('gulp-zip');
const env = readConfig('.env.json', { override: true });
gulp.task('zip', () => {
let now = new Date();
let m = now.getMonth();
let d = now.getDate();
m++;
if(m < 10){m = "0"+m;}
if(d < 10){d = "0"+d;}
let name = now.getFullYear()+'-'+m+'-'+d;
if(typeof options.filename != 'undefined' && options.filename != null){
name += "_"+options.filename;
}
return gulp.src(env.server.dist+"/**")
.pipe(zip(name + ".zip"))
.pipe(gulp.dest(env.server.zipfolder));
});