How to find out nsIZipWriter and nsIZipReader?

I was wondering how to use JavaScript to write and read asynchronous mail messages.

0


source to share


1 answer


Here is an example for reading zip using nsIZipReader , writing to zip is similar. The example reads a zip file from /tmp/example.zip

and prints the contents of the first file to the console.

Notes:



  • I am using nsIInputStreamPump

    for async I / O I found a link to this API in the Streaming Guide on MDN . This interface offers a method .asyncRead

    that takes an object that implements nsIStreamListener

    (s nsIRequestObserver

    ).
  • I compared the execution time of this example with the synchronous zip read example on MDN and found that the reading time used by reading the lock is significantly less (reading the zip file from the RAM disk: 1-2ms to 0.1-0.3ms) ( measured with console.time('foo');

    before reusableStreamInstance.init

    and console.timeEnd('foo');

    after call reusableStreamInstance.readBytes

    )
    .
  • I use .readBytes

    instead .read

    to avoid truncating data if the file contains null bytes.
  • I have not implemented error handling (zip is not existent, zip does not contain a file, zip / file cannot be opened), but I close the zipreader regardless of whether an error occurs.
let { Cc: classes, Cu: utils, Ci: interfaces } = Components;

Cu.import('resource://gre/modules/FileUtils.jsm');

let pathToZip = '/tmp/example.zip';
let nsiFileZip = new FileUtils.File(pathToZip);

let streamListener = {
  buffer: null,
  // nsIRequestObserver
  onStartRequest: function(aRequest, aContext) {
    this.buffer = [];
  },
  // nsIStreamListener
  onDataAvailable:
      function(aRequest, aContext, aInputStream, aOffset, aCount) {
    let reusableStreamInstance = Cc['@mozilla.org/scriptableinputstream;1']
        .createInstance(Ci.nsIScriptableInputStream);
    reusableStreamInstance.init(aInputStream);
    let chunk = reusableStreamInstance.readBytes(aCount);
    this.buffer.push(chunk);
  },
  // nsIRequestObserver
  onStopRequest: function(aRequest, aContext, aStatusCode) {
    console.log('end', aStatusCode);
    var data = this.buffer.join('');
    console.log(data);
  }
};

let pump = Cc['@mozilla.org/network/input-stream-pump;1']
    .createInstance(Ci.nsIInputStreamPump);
let zr = Cc['@mozilla.org/libjar/zip-reader;1']
    .createInstance(Ci.nsIZipReader);
try {
  zr.open(nsiFileZip);
  // null = no entry name filter.
  var entries = zr.findEntries(null);
  while (entries.hasMore()) {
    var entryPointer = entries.getNext();
    var entry = zr.getEntry(entryPointer);
    if (!entry.isDirectory) {
      var stream = zr.getInputStream(entryPointer);
      pump.init(stream, 0, -1, 0, 0, true);
      pump.asyncRead(streamListener, null);
      // For the demo, we only take one file, so break now.
      break;
    }
  }
} finally {
  zr.close();
}

      

+1


source







All Articles