From 193778726e8e3977cfa992caf6ba9bf33671053e Mon Sep 17 00:00:00 2001 From: David Bruant Date: Sat, 19 Jan 2019 13:25:01 +0100 Subject: [PATCH] Read only the necessary bytes when parsing the header --- src/header.js | 44 +++++++++++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/src/header.js b/src/header.js index 9b719d9..f0c4a49 100644 --- a/src/header.js +++ b/src/header.js @@ -8,24 +8,42 @@ export default class Header { } parse(callback) { - fs.readFile(this.filename, (err, buffer) => { + fs.open(this.filename, 'r', (err, fd) => { if (err) throw err; - this.type = buffer.slice(0, 1).toString(this.encoding); - this.dateUpdated = this.parseDate(buffer.slice(1, 4)); - this.numberOfRecords = this.convertBinaryToInteger(buffer.slice(4, 8)); - this.start = this.convertBinaryToInteger(buffer.slice(8, 10)); - this.recordLength = this.convertBinaryToInteger(buffer.slice(10, 12)); + const startBuffer = Buffer.alloc(2); - const result = []; - for (let i = 32, end = this.start - 32; i <= end; i += 32) { - result.push(buffer.slice(i, i+32)); - } + fs.read(fd, startBuffer, 0, 2, 8, (err, bytesRead, buffer) => { + if (err) throw err; - this.fields = result.map(this.parseFieldSubRecord.bind(this)); + const start = this.convertBinaryToInteger(buffer); - callback(this); - }); + const headerBuffer = Buffer.alloc(start); + + fs.read(fd, headerBuffer, 0, start, 0, (err, bytesRead, buffer) => { + if (err) throw err; + + this.type = buffer.slice(0, 1).toString(this.encoding); + this.dateUpdated = this.parseDate(buffer.slice(1, 4)); + this.numberOfRecords = this.convertBinaryToInteger(buffer.slice(4, 8)); + this.start = this.convertBinaryToInteger(buffer.slice(8, 10)); + this.recordLength = this.convertBinaryToInteger(buffer.slice(10, 12)); + + const result = []; + for (let i = 32, end = this.start - 32; i <= end; i += 32) { + result.push(buffer.slice(i, i+32)); + } + + this.fields = result.map(this.parseFieldSubRecord.bind(this)); + + callback(this); + + fs.close(fd, err => { + if (err) throw err; + }) + }) + }) + }) } parseDate(buffer) {