I am trying to read a ZIP file and output it to the browser, get the code that\'s shown on the page and save it as a ZIP file
fs.readFileSync(\'/dir/file.zip
You need to use zlib module of nodejs for these purposes https://nodejs.org/api/zlib.html#zlib_zlib_createunzip_options
ZIP is a binary file type, when you output it in a browser as a text and copy-paste the text to a text editor, you won't get the same value as in the original file (likely web browser will interpret some of its contents as HTML tags, and/or a copy-paste will mangle some binary characters, and/or a text editor itself will mangle them).
What you should do is set appropriate HTTP response headers when serving the file to the browser, so that the browser knows it's a ZIP and can display the user a file download prompt. If you don't send any response headers, browser will just display contents as a text file which doesn't make sense.
Have a look at this question which has a PHP solution:
https://stackoverflow.com/a/10817739/245966
Basically you need to set appropriate Content-Type
and Content-Disposition
header, and (optionally) Content-Length
.
setResponseHeader('Content-Disposition: attachment; filename=myfile.zip');
setResponseHeader('Content-Type: application/zip');
setResponseHeader('Content-Length: ' + fileLengthInBytes);
Replace setResponseHeader
with appropriate call to your HTTP framework which sets the response header.
You're trying to read a zip file as a character encoding (utf-8) which should probably be changed to 'binary'