summaryrefslogtreecommitdiff
path: root/lib/zipfile.js
blob: efe519cc8133c9ca8ab282a31c2346a4c34e6861 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
var JSZip = require("jszip");

var promises = require("./promises");

exports.openArrayBuffer = openArrayBuffer;
exports.joinZipPath = joinZipPath;

function openArrayBuffer(arrayBuffer) {
    var zipFile = new JSZip(arrayBuffer);
    function exists(name) {
        return zipFile.file(normaliseName(name)) !== null;
    }
    
    function read(name, encoding) {
        var array = zipFile.file(normaliseName(name)).asUint8Array();
        var buffer = new Buffer(array);
        if (encoding) {
            return promises.when(buffer.toString(encoding));
        } else {
            return promises.when(buffer);
        }
    }
    
    function write(name, contents) {
        zipFile.file(normaliseName(name), contents);
    }
    
    function toBuffer() {
        return zipFile.generate({type: "nodebuffer"});
    }
    
    return {
        exists: exists,
        read: read,
        write: write,
        toBuffer: toBuffer
    };
}

function normaliseName(name) {
    if (name.charAt(0) === "/") {
        return name.substr(1);
    } else {
        return name;
    }
}

function joinZipPath(first, second) {
    if (second.charAt(0) === "/") {
        return second;
    } else {
        // In general, we should check first and second for trailing and leading slashes,
        // but in our specific case this seems to be sufficient
        return first + "/" + second;
    }
}