Question:
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:
1 2 3 4 5 6 7 8 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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:
- Change the body of the request to a base64 string (jszip:
generateAsync({type: 'base64'})
) - Make the API Gateway serve binary content: https://medium.com/nextfaze/binary-responses-with-serverless-framework-and-api-gateway-5fde91376b76
Answer:
You can try encoding the response as Base64 encoded string by adding isBase64Encoded: true
in the response object.