node.jszipnestjszip

How can I order files when adding them to zip by using jszip node js


Actually I am adding an array of files to a zip by using jszip package. the package adds my files based on date so I want to see my first element of array as the first file in zip but the package add one by one based on date and my first element goes to last and last element of array comes to first position.

I loop my array and want to add items one by one to zip file. without ordering them by date.


Solution

  • I attempted to try out the code and it is working fine... Here is the code:

    var JSZip = require("jszip");
    var fs = require("fs");
    var zip = new JSZip();
    
    const qrCodes = {
        qrCodes: [
            "b",
            "a",
            "c"
        ],
        tagsInfo: {
            "a": {
                tagId: "a_id",
                tagCode: "a_code"
            },
            "b": {
                tagId: "b_id",
                tagCode: "b_code"
            },
            "c": {
                tagId: "c_id",
                tagCode: "c_code"
            }
        }
    }
    
    // looping the array
    qrCodes.qrCodes.map((qrCode) => {
        zip.file( `${qrCodes.tagsInfo[qrCode].tagId}_${qrCodes.tagsInfo[qrCode].tagCode}.svg`, `${qrCode}` );
    });
    
    // saving the zip file
    zip
    .generateNodeStream({type:'nodebuffer',streamFiles:true})
    .pipe(fs.createWriteStream('out.zip'))
    .on('finish', function () {
        // JSZip generates a readable stream with a "end" event,
        // but is piped here in a writable stream which emits a "finish" event.
        console.log("out.zip written.");
    });
    

    I am on macOS so I have used zipinfo tool to check the order:

    NodeJSTest % zipinfo out.zip 
    Archive:  out.zip
    Zip file size: 391 bytes, number of entries: 3
    -rw----     2.0 fat        1 bl stor 22-Nov-22 07:47 b_id_b_code.svg
    -rw----     2.0 fat        1 bl stor 22-Nov-22 07:47 a_id_a_code.svg
    -rw----     2.0 fat        1 bl stor 22-Nov-22 07:47 c_id_c_code.svg
    3 files, 3 bytes uncompressed, 3 bytes compressed:  0.0%
    

    Although if I extract directly in Finder, it sorts it via Name, but still the contents of zip itself (without extracting) is ordered correctly! If you are on windows, you can check the order by opening zip in say 7zip and check the order without extracting it...