Created
September 29, 2012 16:08
-
-
Save mfncooper/3804475 to your computer and use it in GitHub Desktop.
Reading a zip file header with reify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var path = require('path'); | |
var exists = fs.existsSync || path.existsSync; | |
var reified = require('reified'), | |
StructT = reified.StructType, | |
NumT = reified.NumericType, | |
Uint16 = NumT.Uint16, | |
Uint32 = NumT.Uint32; | |
reified.defaultEndian = 'LE'; | |
function inspect(o) { console.log(require('util').inspect(o, false, 6)); } | |
var ZipHeader = new StructT('ZipHeader', { | |
signature: Uint32, | |
thisDiskNo: Uint16, | |
cdStartDiskNo: Uint16, | |
cdCountThis: Uint16, | |
cdCountAll: Uint16, | |
cdBytes: Uint32, | |
cdOffset: Uint32, | |
commentLen: Uint16 | |
}); | |
function Zippy(buffer, filename) { | |
this.filename = filename; | |
this.name = filename.slice(0, -path.extname(filename).length); | |
this.index = new ZipHeader(buffer); | |
inspect(this.reify()); | |
} | |
Zippy.prototype.reify = function reify() { | |
return Object.keys(this).reduce(function (r, s) { | |
r[s] = this[s].reify ? this[s].reify() : this[s]; | |
return r; | |
}.bind(this), {}); | |
} | |
Zippy.load = function load(filename) { | |
var resolved = path._makeLong(path.resolve('.', filename)); | |
if (exists(resolved)) { | |
// Zip header is last 22 bytes of file | |
var filebuf = fs.readFileSync(resolved), | |
hdrbuf = filebuf.slice(filebuf.length - 22, filebuf.length); | |
return new Zippy(hdrbuf, filename); | |
} else { | |
throw new Error(resolved + ' not found'); | |
} | |
} | |
Zippy.load(process.argv[2]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment