2

I used the node-archiver to zip files as follows. But I get corrupted zip file.

app.get('/download', async (req, res) => {

    const arch = archiver('zip');
    arch.append('abc', { name: 'abc.txt'});
    arch.append('cdf', { name: 'cdf.txt'});

    res.attachment('test.zip').type('zip');
    arch.pipe(res);
    arch.finalize();
});

I modified the code to save to the file system directly. With this code, I get a working zip file created on filesystem.

app.get('/download', async (req, res) => {


    const arch = archiver('zip');
    arch.append('abc', { name: 'abc.txt'});
    arch.append('cdf', { name: 'cdf.txt'});

    const output = fs.createWriteStream('./test.zip');
    arch.pipe(output);
    arch.finalize();
});

Why is zip file getting corrupted while sent via express res object? What would be the fix?

Edit: If I use output format as tar instead of zip the it works without any problem.

const arch = archiver('tar');
Pavan Kumar
  • 1,715
  • 1
  • 24
  • 48

1 Answers1

0

I think you need to close the response stream too:

app.get('/download', async (req, res) => {

    const arch = archiver('zip');
    arch.append('abc', { name: 'abc.txt'});
    arch.append('cdf', { name: 'cdf.txt'});

    res.attachment('test.zip').type('zip');
    arch.on('end', () => res.end()); // end response when archive stream ends
    arch.pipe(res);
    arch.finalize();
});
Sam
  • 5,375
  • 2
  • 45
  • 54