javascriptreactjsjszip

JSZip generateAsync TypeError: e3.charCodeAt is not a function



import JSZip from 'jszip';
import FileSaver from 'file-saver';

  const exportData = (evt: any) => {
  var reportFileName = 'myreport.zip';
  const ziptool = new JSZip();
  var blob_raw_data = { id: 'xxxxxxx', bm: 0, em: 1500 }; 
  var jsonse = JSON.stringify(blob_raw_data, null, '\t');
  var bytes = new TextEncoder().encode(jsonse);
  var blob = new Blob([bytes], { type: "text/plain;charset=utf-8" });
  ziptool.file('values.txt', blob, {binary: false});
  ziptool.generateAsync({ type: "blob" })
    .then(function (blob_data) {
      FileSaver.saveAs(blob_data, reportFileName);
    }
  );

The error message:


Uncaught (in promise) 
TypeError: e3.charCodeAt is not a function
    at jszip.js?v=79504123:739:68
    at s.utf8encode (jszip.js?v=79504123:742:12)
    at l.processChunk (jszip.js?v=79504123:772:31)
    at s. (jszip.js?v=79504123:596:16)
    at s.emit (jszip.js?v=79504123:588:116)
    at s.push (jszip.js?v=79504123:571:16)
    at s._tick (jszip.js?v=79504123:563:40)
    at s._tickAndRepeat (jszip.js?v=79504123:547:82)
    at jszip.js?v=79504123:537:126

I checked the jszip.js file, it died in this function:


        s.utf8encode = function(e2) {
          return h.nodebuffer ? r.newBufferFrom(e2, "utf-8") : function(e3) {
            var t2, r2, n2, i2, s2, a2 = e3.length, o2 = 0;
            for (i2 = 0; i2 >> 6 : (r2 >> 12 : (t2[s2++] = 240 | r2 >>> 18, t2[s2++] = 128 | r2 >>> 12 & 63), t2[s2++] = 128 | r2 >>> 6 & 63), t2[s2++] = 128 | 63 & r2);
            return t2;
          }(e2);


Solution

  • Instead of manually encoding data and creating a Blob, pass the string data directly to JSZip. This avoids the need for explicit encoding and relies on JSZip's internal handling of strings. Hope this helps.

    const exportData = () => {
     const reportFileName = 'myreport.zip';
     const ziptool = new JSZip();
     const blob_raw_data = { id: 'xxxxxxx', bm: 0, em: 1500 }; 
     const jsonse = JSON.stringify(blob_raw_data, null, '\t');
    
     // Add the string data directly to JSZip
     ziptool.file('values.txt', jsonse);
    
     ziptool.generateAsync({ type: 'blob' })
      .then(blob_data => {
         FileSaver.saveAs(blob_data, reportFileName);
      })
      .catch(error => {
        console.error('Error generating ZIP file:', error);
      });
    };