John
John

Reputation: 1751

NodeJS ZIP file downloaded corrupt

i im using this code to generate mysql dump in memory then zip that sql file with password from memory and write it to HDD so that i can pipe it to client...

            /* DUMP - database */
            var mysqldump = spawn('mysqldump', ['-u', 'root', '-p'+db_pass, db_name]);
            var mysqlzip  = spawn('zip', ['--password', db_zip]);

            /* OUTPUT - to zip & pv */
            mysqldump.stdout.pipe(mysqlzip.stdin)
            mysqlzip.stdout.pipe(fs.createWriteStream(process.env.PWD+'/'+results[Object.keys(results)[0]]+'-'+date+'.zip'));

            mysqlzip.on('close', function () {
                console.log('ZIP File Created!');

                /* PIPE - backup zip */
               var zip = fs.createReadStream(process.env.PWD+'/'+req.params.zip, 'binary').pipe(res);

               /* DELETE - backup zip */
              zip.on('finish', function() {
                   fs.unlink(process.env.PWD+'/'+rows[0].name+'-'+date+'.zip', function() {});
                   console.log('deleting zip file...');
                  res.end();
              });   
          });

And client side to download this file:

$.ajax({ type: 'GET', url: '/api/backup', success: function(res){ console.log('downloading backup success'); } });

The problem is that ZIP file size is 1.280 KB and download file size is sometimes 10KB sometimes 2.158KB and so and..and when opening zip file i get error message that zip file is corrupt.

So i define to read ZIP file as 'binary' and to pipe it to client response...but i get always zip file corrupt.

Upvotes: 2

Views: 2427

Answers (1)

John
John

Reputation: 1751

Just removing 'binary' from:

/* PIPE - backup zip */
var zip = fs.createReadStream(process.env.PWD+'/'+req.params.zip, 'binary').pipe(res);

To be:

/* PIPE - backup zip */
var zip = fs.createReadStream(process.env.PWD+'/'+req.params.zip).pipe(res);

Solves the problem..now zip file is correct downloaded...it opens fine in zip and size matches the original on server...

Upvotes: 1

Related Questions