Nathan Nathan - 1 month ago 23
Node.js Question

Trying to donwload a file from aws s3 into nodejs writeStream

I am trying to download a file from s3 and directly put into into a file on the filesystem using a writeStream in nodejs. This is my code:

downloadFile = function(bucketName, fileName, localFileName) {
//Donwload the file
var bucket = new AWS.S3({
params: { Bucket: bucketName },
signatureVersion: 'v4'
});
var file = require('fs').createWriteStream(localFileName);
var request = bucket.getObject({ Key: fileName });
request.createReadStream().pipe(file);
request.send();
return request.promise();
}


Running this function I get this error:

Uncaught Error: write after end


What is happening? Is the file closed before the write is finished? Why?

Answer
var s3 = new AWS.S3({
    accessKeyId: accessKeyId,
    secretAccessKey: secretAccessKey
}),
file = fs.createWriteStream(localFileName);
s3
.getObject({
    Bucket: bucketName,
    Key: fileName
})
.on('error', function (err) {
    console.log(err);
})
.on('httpData', function (chunk) {
    file.write(chunk);
})
.on('httpDone', function () {
    file.end();
})
.send();