daraosn / node-zip

217 stars 38 forks source link

zip file obtained cant be opened #32

Open markl-vesper opened 5 years ago

markl-vesper commented 5 years ago

I'm using node-zip package in AWS Lambda function to serve up a couple of files from S3 bucket to client via API/GW.

API Call via Postman is returning data however when I save that data to a .zip file and try to extract I'm getting told its not a valid zip file.

Below is example of code without all the S3 stuff as its not relevant

const zip = require("node-zip")();

// gets files from S3 OK then zips them up

zip.file(certFilePath, getCRTResponse);

zip.file(privateKeyPath, getPrivateKeyResponse);

const data = zip.generate({ base64: false, compression: "DEFLATE" });

responseBody = {
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST",
        "Content-type": "application/zip",
        "Content-Disposition": "attachment; filename='" + certPath[3] + "-" + event.pathParameters.serial + ".zip'"
    },
    body: data
};

callback(null, responseBody);
chaitanya-mahamuni commented 5 years ago

I am also facing a similar issue when I am not storing zip on disk and trying to send data as "Content-Disposition" set to "attachment". :(

markl-vesper commented 5 years ago

@chaitanya-mahamuni

I moved on and re-architected the api since then and no longer need zip functionality. Sorry I dont have a workaround for you.

chaitanya-mahamuni commented 5 years ago

@markl-vesper: Thanks for the update. If I get any solution, I'll post it here.

chaitanya-mahamuni commented 5 years ago

@markl-vesper: I got it working. Basically, you need to set encoding as "binary" for the response.

Refer to sample code below. I am using "hapi" as the application server. In case of "hapi", default encoding for response is "utf8".

const zip = require("node-zip")();

zip.file("file_1.txt", "Some test data");
zip.file("file_2.txt", "Some test data again");

const data = zip.generate({ base64: false, compression: "DEFLATE" });

reply(data)
    .code(200)
    .encoding('binary')
    .header("Content-Type", "application/zip")
    .header("Content-Disposition", "attachment; filename=zip_name.zip");

Let me know if you get a chance to give it a try and if it works for you.