Home > Software design >  Nodejs: Downloading file from s3 and then writing to filesystem
Nodejs: Downloading file from s3 and then writing to filesystem

Time:11-17

I am able to download the file from s3 bucket like so:

 const fileStream = s3.getObject(options).createReadStream();
    const writableStream = createWriteStream(
        "./files/master_driver_profile_pic/image.jpeg"
    );
    fileStream.pipe(fileStream).pipe(writableStream);

But the image is not getting written properly. Only a little bit of the image is visible and the rest is blank.

CodePudding user response:

I think you should first createWriteStream and then createReadStream. (Check the docs)

var s3 = new AWS.S3();  
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};  

var file = require('fs').createWriteStream('/path/to/file.jpg');
s3.getObject(params).createReadStream().pipe(file);  

OR

you can go without streams:

// Download file
let content = await (await s3.getObject(params).promise()).Body;

// Write file
fs.writeFile(downloadPath, content, (err) => {
   if (err) { console.log(err); }
});
  • Related