Node.js archiver has unclear behavior

122 views Asked by At

I'm using the following code to zip an entire folder that consists of .txt files only and to send to the client as a .zip file.

var time = new Date().getTime();
var userId = parseInt(req.params.userId);
console.log("User ID: "+userId);
var output = fs.createWriteStream('user_archive/temp-'+userId+'.zip');
var arch = archiver('zip');

output.on('close', function () {
    console.log(arch.pointer() + ' total bytes\n\r__');

    res.header('Content-disposition', 'attachment; filename=archive-'+time+'.zip');
    res.header('Content-type', 'application/octet-stream');
    var filestream = fs.createReadStream('user_archive/temp-'+userId+'.zip');
    filestream.pipe(res);

});

arch.on('error', function(err){
    throw err;
});

arch.pipe(output);
arch.bulk([
    { expand: true, cwd: 'user_archive/temp-'+userId+'/', src: ['*.txt'], dest: 'messages-'+time}
]).finalize();

The problem I'm facing is that I am not receiving the same number of bytes when testing this code and console.log(arch.pointer() + ' total bytes\n\r__'); gives me values from 22 bytes, which correspond to an incorrect archive, to the correct number of bytes. Another thing to mention, after 5-6 consecutive tests I receive a correct archive until I stop and restart the node. Then it happens again: 5 incorrect archives followed by correct archives. My question: why this unclear behavior?

0

There are 0 answers