How to find out nsIZipWriter and nsIZipReader?

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


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/

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


  • 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;


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

let streamListener = {
  buffer: null,
  // nsIRequestObserver
  onStartRequest: function(aRequest, aContext) {
    this.buffer = [];
  // nsIStreamListener
      function(aRequest, aContext, aInputStream, aOffset, aCount) {
    let reusableStreamInstance = Cc[';1']
    let chunk = reusableStreamInstance.readBytes(aCount);
  // nsIRequestObserver
  onStopRequest: function(aRequest, aContext, aStatusCode) {
    console.log('end', aStatusCode);
    var data = this.buffer.join('');

let pump = Cc[';1']
let zr = Cc[';1']
try {;
  // 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.
} finally {




All Articles