Search code examples
javascriptnode.jsaws-sdk-nodejs

Downloading images from S3 with AWS-SDK Nodejs downloads a corrupt image


I'm trying to download images from aws s3 using the AWS-SDK for nodejs. The file does get downloaded and the size is also correct. However, the file is corrupted and shows Decompression error in IDAT.

async download(accessKeyId, secretAccessKey, region, bucketName, baseImage) {
        console.log("Entered download");
        const s3 = new AWS.S3({region: region});
        const params = {
             Bucket: bucketName,
             Key: `base/${baseImage}`
         };

        const outStream = fs.createWriteStream(this.config.baseFolder + baseImage);
        const awsStream = s3.getObject(params, (uerr, data) => {
            if(uerr) throw uerr;
            console.log(`Base file downloaded successfully!`)
        }).createReadStream().pipe(outStream);

        awsStream.on('end', function() {
            console.log("successfully Downloaded");
        }).on('error', function() {
            console.log("Some error occured while downloading");
        });
    }

Here's the link I followed - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html The file should get downloaded without any error. I tried searching on stack and there are some similar questions, however, they are using nodejs to deliver the output to the frontend and those solutions aren't working for me.


Solution

  • It wasn't necessary to make a mess and do all this... It can directly be achieved by -

    async download(accessKeyId, secretAccessKey, region, bucketName, baseImage) {
            console.log("Starting Download... ")
            const s3 = new AWS.S3({
                accessKeyId: accessKeyId,
                secretAccessKey: secretAccessKey,
                region: region
            });
            const params = {
                Bucket: bucketName,
                Key: `base/${baseImage}`
             };
    
            s3.getObject(params, (err, data) => {
                if(err) console.error(err);
                console.log(this.config.baseFolder + baseImage);
                fs.writeFileSync(this.config.baseFolder + baseImage, data.Body);
                console.log("Image Downloaded.");
            });
        }