node.jstypescriptarchiverjs

How to control the order of zipped directories and files with "archiver.js"?


I am using archiver to zip two folders x and y:

const out = ... // file write stream
...
const zip = archiver('zip', {});
zip.on('error', (err: Error) => { throw err; });

zip.pipe(out);
zip.directory('x', 'x');
zip.directory('y', 'y');
zip.finalize();

The zip file is Ok but but unzip -l shows x and y interleaved.
(Looks like the archiver traverses x and y in BFS-order).

x/x1
x/x2
y/y1
y/y2
x/x1/x11.txt
x/x2/x21.txt
y/y1/y11.txt

I'd like to zip x and y in DFS-order so unzip -l shows:

x/x1
x/x1/x11.txt
x/x2
x/x2/x21.txt
y/y1
y/y1/y11.txt
y/y2

How can I control the order of zipped directories and files ?


Solution

  • You can use glob() method instead of directory() to match files using a glob pattern.

    It will append files in DFS-order.

    The instruction should look like:

    zip.glob('{x,y}/**/*');
    

    Full code example:

    import fs = require('fs');
    import archiver = require('archiver');
    
    let out = fs.createWriteStream(process.cwd() + '/example.zip');
    
    const zip = archiver('zip', {});
    zip.on('error', (err: Error) => { throw err; });
    
    zip.pipe(out);
    zip.glob('{x,y}/**/*');
    zip.finalize();