diff options
| author | Michael Williamson <mike@zwobble.org> | 2017-01-23 18:23:50 +0000 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2017-01-23 18:24:43 +0000 |
| commit | 635b04a5e46f9a8e09d72b6e593b056106706110 (patch) | |
| tree | 11691981e2d07fb20976d103d58baf7dc9a1e2d1 | |
| parent | 840dcaae21c2b8b478e5f1bfed599885f6177672 (diff) | |
Strip leading slashes from names when getting zip entries
| -rw-r--r-- | lib/zipfile.js | 14 | ||||
| -rw-r--r-- | test/zipfile.tests.js | 24 |
2 files changed, 35 insertions, 3 deletions
diff --git a/lib/zipfile.js b/lib/zipfile.js index 91c5f04..efe519c 100644 --- a/lib/zipfile.js +++ b/lib/zipfile.js @@ -8,11 +8,11 @@ exports.joinZipPath = joinZipPath; function openArrayBuffer(arrayBuffer) { var zipFile = new JSZip(arrayBuffer); function exists(name) { - return zipFile.file(name) !== null; + return zipFile.file(normaliseName(name)) !== null; } function read(name, encoding) { - var array = zipFile.file(name).asUint8Array(); + var array = zipFile.file(normaliseName(name)).asUint8Array(); var buffer = new Buffer(array); if (encoding) { return promises.when(buffer.toString(encoding)); @@ -22,7 +22,7 @@ function openArrayBuffer(arrayBuffer) { } function write(name, contents) { - zipFile.file(name, contents); + zipFile.file(normaliseName(name), contents); } function toBuffer() { @@ -37,6 +37,14 @@ function openArrayBuffer(arrayBuffer) { }; } +function normaliseName(name) { + if (name.charAt(0) === "/") { + return name.substr(1); + } else { + return name; + } +} + function joinZipPath(first, second) { if (second.charAt(0) === "/") { return second; diff --git a/test/zipfile.tests.js b/test/zipfile.tests.js index 52389a8..f6c38d4 100644 --- a/test/zipfile.tests.js +++ b/test/zipfile.tests.js @@ -17,6 +17,30 @@ test('file in zip can be read after being written', function() { }); }); +test('leading slash in path is stripped if set when reading', function() { + var zip = emptyZipFile(); + assert(!zip.exists("/song/title")); + + zip.write("song/title", "Dark Blue"); + + assert(zip.exists("/song/title")); + return zip.read("/song/title", "utf8").then(function(contents) { + assert.equal(contents, "Dark Blue"); + }); +}); + +test('leading slash in path is stripped if set when writing', function() { + var zip = emptyZipFile(); + assert(!zip.exists("song/title")); + + zip.write("/song/title", "Dark Blue"); + + assert(zip.exists("song/title")); + return zip.read("song/title", "utf8").then(function(contents) { + assert.equal(contents, "Dark Blue"); + }); +}); + function emptyZipFile() { var zip = new JSZip(); var buffer = zip.generate({type: "arraybuffer"}); |
