Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node writes corrupted .xlsx files after download

I`m using "xlsx" module on serverside. My server's gettings .xlsx files from client. It works great when file is uploaded with multipart. But when i'm trying to download files from Google Drive or Dropbox, i alway receive corrupted .xlsx files.

Function to download files from Google Drive.

service.files.get({
                auth: auth,
                fileId: fileId,
                alt: 'media'
            }, function (err, response) {
                if (err) {
                    res.status(400).json({message: "Error while downloading"});
                } else {                        
                    fs.writeFileSync(req.body.fileName, response);
                    var data = xlsParser.parse(fs.readFileSync(req.body.fileName));
                    res.json(data);
                }
            });

Parser code

module.exports = {
parse: function (file) {
    var workSheet = xlsx.read(file, {});
    return Object.keys(workSheet.Sheets).map(function(name) {
        var sheet = workSheet.Sheets[name];
        return {name, data: xlsx.utils.sheet_to_json(sheet, {raw: false})}
    })
}}

Files on Google Drive are valid. After writing them with node I can't open them. Error i get

\node_modules\jszip\lib\dataReader.js:25
        throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
        ^

Error: End of data reached (data length = 1771452, asked index = 1771464). Corrupted zip ?
like image 710
Vitaliy Rokossovyk Avatar asked Nov 09 '22 06:11

Vitaliy Rokossovyk


1 Answers

While using xlsx and exceljs modules, both the writeFileSync and readFileSync must be promises and you should wait for them to resolve before performing the next operation.

like image 140
Gaurav Avatar answered Nov 15 '22 05:11

Gaurav