Search code examples
node.jsamazon-web-servicesaws-serverless

Serve zip file from AWS Lambda


I need an endpoint (serverless) that serves a series of files compressed in a zip file. To do this I am using node-zip. This works locally to create a simple zip file with a flat file text:

const fs = require('fs')
const zip = new require('node-zip')()

const flat_text = 'This is a flat text file'

zip.file('a_file.txt', flat_text)
fs.writeFileSync('/tmp/a_file.zip', zip.generate({base64: false, compression: 'DEFLATE'}), 'binary')

But when I try to implement it in a lambda the downloaded zip file is corrupted:

module.exports.weekly = async (event, context) => {
    const flat_text = 'This is a flat text file'
    zip.file('a_file.txt', flat_text)
    return {
        headers: {
            'Content-Type': 'application/zip, application/octet-stream',
            'Content-disposition': `attachment; filename=${`any_name_${new Date().toJSON().slice(0, 10)}.zip`}`
        },
        body:  zip.generate({base64: false, compression: 'DEFLATE'}),
        statusCode: 200
    }
}

Why do I get a corrupted zip file?

Update

What I did in the end to fix this:


Solution

  • You can try encoding the response as Base64 encoded string by adding isBase64Encoded: true in the response object.