nsIZipReader

This interface provides methods for reading compressed (zip) files.
Inherits from: nsISupports Last changed in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7)

Implemented by: @mozilla.org/libjar/zip-reader;1. To create an instance, use:

var zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"]
                .createInstance(Components.interfaces.nsIZipReader);

About character sets and code pages

Note: nsIZipReader has a code page problem; that is, in the ZIP specification, filenames are supposed to use 7-bit ASCII; however, most modern filesystems use 8 bit code pages, such as UTF-8. This can mismatch characters in the nsIZipReader API.

Starting in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), the nsIZipReader API supports a limited 8 bit code page usage. All functions now pass the filenames (both in and out) as AUTF8String. So you can now read and extract  what you wrote with nsIZipWriter. If you show filenames from the findEntries() result in the user interface,  the character matching is only fine on UTF-8  ZIP archives.

Method overview

void close();
void extract(in AUTF8String zipEntry, in nsIFile outFile);
void extract(in string zipEntry, in nsIFile outFile); Obsolete since Gecko 10
nsIUTF8StringEnumerator findEntries(in AUTF8String aPattern);
nsIUTF8StringEnumerator findEntries(in string aPattern); Obsolete since Gecko 10
nsIPrincipal getCertificatePrincipal(in AUTF8String aEntryName);
nsIPrincipal getCertificatePrincipal(in string aEntryName); Obsolete since Gecko 10
nsIZipEntry getEntry(in AUTF8String zipEntry);
nsIZipEntry getEntry(in string zipEntry); Obsolete since Gecko 10
nsIInputStream getInputStream(in AUTF8String zipEntry);
nsIInputStream getInputStream(in string zipEntry); Obsolete since Gecko 10
nsIInputStream getInputStreamWithSpec(in AUTF8String aJarSpec, in AUTF8String zipEntry);
nsIInputStream getInputStreamWithSpec(in AUTF8String aJarSpec, in string zipEntry); Obsolete since Gecko 10
boolean hasEntry(in AUTF8String zipEntry);
void init(in nsIFile zipFile); Obsolete since Gecko 1.9
void open(in nsIFile zipFile);
void openInner(in nsIZipReader zipReader, in AUTF8String zipEntry);
void openInner(in nsIZipReader zipReader, in string zipEntry); Obsolete since Gecko 10
void test(in AUTF8String aEntryName);
void test(in string aEntryName); Obsolete since Gecko 10

Attributes

Attribute Type Description
file nsIFile The file that represents the zip with which this zip reader was initialized. Read only.
manifestEntriesCount PRUint32 The number of entries in the manifest. Read only.

Methods

close()

Closes a zip reader. Subsequent attempts to extract() files or read from its input stream will result in an error. Subsequent attempts to access a nsIZipEntry obtained from this zip reader will cause unspecified behavior.

void close();
Parameters

None.

Example demonstrating this function: List Contents of XPI and Read File Contents

extract()

Extracts a zip entry into a local file specified by outFile. The entry must be stored in the zip in either uncompressed or DEFLATE-compressed format for the extraction to be successful. If the entry is a directory, the directory will be extracted non-recursively.

void extract(
  in AUTF8String zipEntry,
  in nsIFile outFile
);
Parameters
zipEntry
The zip entry to extract.
outFile
The local file destination used to extract the zip entry.

Requires Gecko 1.9 (Firefox 3)

findEntries()

Returns a string enumerator containing the matching entry names.

nsIUTF8StringEnumerator findEntries(
  in AUTF8String aPattern
);
Parameters
aPattern
A regular expression used to find matching entries in the zip file. Set this parameter to null (javascript) or EmptyCString() (c++) to get all entries; otherwise, use the following syntax:
  • * matches anything.
  • ? matches one character.
  • $ matches the end of the string.
  • [abc] matches one occurrence of a, b, or c. The only character that must be escaped inside the brackets is ]. ^ and - must never appear in the first and second positions within the brackets, respectively. (In the former case, the behavior specified for '[^az]' will happen.)
  • [a-z] matches any character between a and z. The characters a and z must either both be letters or both be numbers, with the character represented by 'a' having a lower ASCII value than the character represented by 'z'.
  • [^az] matches any character except a or z. If ] is to appear inside the brackets as a character to not match, it must be escaped.
  • Pat~pat2 returns matches to the pattern 'pat' which do not also match the pattern 'pat2'. This may be used to perform filtering upon the results of one pattern to remove all matches which also match another pattern. For example, because '*' matches any string and '*z*' matches any string containing a 'z', '*~*z*' will match all strings except those containing a 'z'. Note that a pattern may not use '~' multiple times, so a string such as '*~*z*~*y*' is not a valid pattern.
  • (foo|bar) will match either the pattern foo or the pattern bar. Neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above.
  • \ will escape a special character. Escaping is required for all special characters unless otherwise specified.
  • All other characters match case-sensitively.

 

An aPattern not conforming to this syntax has undefined behavior.

Return value

The nsIUTF8StringEnumerator containing the matching entry names.

Exceptions thrown
NS_ERROR_ILLEGAL_VALUE
On many but not all invalid aPattern values.

Requires Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

getCertificatePrincipal()

Returns an object describing the entity which signed an entry. parseManifest must be called first. If aEntryName is an entry in the jar, getInputStream() must be called after parseManifest. If aEntryName is an external file which has meta-information stored in the jar, verifyExternalFile (not yet implemented) must be called before getPrincipal.

nsIPrincipal getCertificatePrincipal(
  in string aEntryName
);
Parameters
aEntryName
Missing Description
Return value

An nsIPrincipal.

Example demonstrating this function: List Contents of XPI and Read File Contents

getEntry()

Returns a nsIZipEntry describing a specified zip entry.

nsIZipEntry getEntry(
  in AUTF8String zipEntry
);
Parameters
zipEntry
The zip entry.
Return value

The nsIZipEntry for the given zip entry.

Example demonstrating this function: List Contents of XPI and Read File Contents

getInputStream()

Returns an input stream containing the contents of the specified zip entry.

nsIInputStream getInputStream(
  in AUTF8String zipEntry
);
Parameters
zipEntry
The name of the entry to open() the stream from.
Return value

The nsIInputStream containing the contents of the specified zip entry.

Example demonstrating this function: List Contents of XPI and Read File Contents

Requires Gecko 1.9 (Firefox 3)

getInputStreamWithSpec()

Returns an input stream containing the contents of the specified zip entry. If the entry refers to a directory (ends with '/'), a directory stream is opened, otherwise the contents of the file entry is returned.

nsIInputStream getInputStreamWithSpec(
  in AUTF8String aJarSpec,
  in AUTF8String zipEntry
);
Parameters
aJarSpec
The Spec of the URI for the JAR (only used for directory streams).
zipEntry
The name of the entry to open() the stream from.
Return value

The nsIInputStream containing the contents of the specified zip entry.

Requires Gecko 1.9 (Firefox 3)

hasEntry()

Checks whether the zipfile contains an entry specified by zipEntry.

boolean hasEntry(
  in AUTF8String zipEntry
);
Parameters
zipEntry
The zip entry.
Return value

Boolean value, true if the zip entry exists, false is it does not exist.

Obsolete since Gecko 1.9 (Firefox 3)

init()

Initializes a zip reader after construction.

void init(
  in nsIFile zipFile
);
Parameters
zipFile
Zip file to initialize.

open()

Opens a zip file for reading. It is allowed to open with another file, but it needs to be closed first with close().

Note: Prior to Gecko 1.9 you first had to call init()"."

void open(
  in nsIFile zipFile 
);
Parameters
zipFile
The zip file to open.

Example demonstrating this function: List Contents of XPI and Read File Contents

Requires Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

openInner()

Opens a zip file inside a zip file for reading.

void openInner(
  in nsIZipReader zipReader, 
  in AUTF8String zipEntry
);
Parameters
 
zipReader
The zipReader object.
zipEntry
The zip entry.

test()

Tests the integrity of the archive by performing a CRC check on each item expanded into memory. If an entry is specified the integrity of only that item is tested. If null (javascript) or EmptyCString() (c++) is passed in the integrity of all items in the archive are tested.

void test(
  in AUTF8String aEntryName
);
Parameters
aEntryName
The single entity to check or null for checking all entries in the archive.

Examples

List contents of XPI and read file contents

This example uses findEntries, getEntry, getInputStream, open, and close. It also uses nsIScriptableInputStream to read the stream returned by getInputStream. XPI files are ZIP files, just Firefox needs the extension to be XPI. Change "PortableTester@jetpack.xpi" to the name of a XPI file in your extensions folder. Then you can copy and paste this code in scratchpad to run it.

    var zr = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(Ci.nsIZipReader);
    Cu.import('resource://gre/modules/osfile.jsm');
    Cu.import('resource://gre/modules/FileUtils.jsm');
    
    var reusableStreamInstance = Cc['@mozilla.org/scriptableinputstream;1'].createInstance(Ci.nsIScriptableInputStream);
    
    var pathToXpiToRead = OS.Path.join(OS.Constants.Path.profileDir, 'extensions', 'PortableTester@jetpack.xpi');
    var nsiFileXpi = new FileUtils.File(pathToXpiToRead);
    
    //Services.ww.activeWindow.alert(pathToXpiToRead);
    
    try {
      zr.open(nsiFileXpi); //if file dne it throws here
      var entries = zr.findEntries('*'); //we use asterik because we want EVERYTHING listed out
      while (entries.hasMore()) {
        var entryPointer = entries.getNext(); //just a string of "zip path" (this means path to file in zip, and it uses forward slashes remember)
        var entry = zr.getEntry(entryPointer); // should return true on `entry instanceof Ci.nsIZipEntry`
        console.log('entryPointer', entryPointer);
        /* CONSOLE OUTPUT
         * "entryPointer" "bootstrap.js" Scratchpad/1:18
         */
        console.info('entry', entry);
        /* CONSOLE OUTPUT
         * "entry" XPCWrappedNative_NoHelper { QueryInterface: QueryInterface(), compression: Getter, size: Getter, realSize: Getter, CRC32: Getter, isDirectory: Getter, lastModifiedTime: Getter, isSynthetic: Getter, permissions: Getter, compression: 8 } Scratchpad/1:19
         */
        if (!entry.isDirectory) {
            var inputStream = zr.getInputStream(entryPointer);
            reusableStreamInstance.init(inputStream);
            var fileContents = reusableStreamInstance.read(entry.realSize);
            console.log('contenst of file=', fileContents);
        } else {
            console.log('is directory, no stream to read');
        }
      }
    } catch (ex) {
      console.warn('exception occured = ', ex);
      if (ex.name == 'NS_ERROR_FILE_NOT_FOUND') {
        Services.ww.activeWindow.alert('XPI at path does not exist!\n\nPath = ' + pathToXpiToRead);
      }
    } finally {
      zr.close();
      console.log('zr closed');
    }

See also

Document Tags and Contributors

 Last updated by: Brettz9,