Skip to content

Instantly share code, notes, and snippets.

@leober-ramos33
Last active March 11, 2019 18:58
Show Gist options
  • Save leober-ramos33/abce54a02a2f573e4db67e6c202a1fb2 to your computer and use it in GitHub Desktop.
Save leober-ramos33/abce54a02a2f573e4db67e6c202a1fb2 to your computer and use it in GitHub Desktop.
Hexadecimal File API (JavaScript)
/**
* hexfile.js by Marc - https://github.com/marcrobledo
*
* https://github.com/marcrobledo/acnl-editor
*/
import { saveAs } from 'file-saver'
class HexFile {
/**
* Creates a instance of a Hexadecimal File
*
* @param {File} source The File to be a Hexadecimal file
*/
constructor (source) {
if (typeof source === 'object' && source.name && source.size) {
this.file = source
this.fileName = this.file.name
this.fileSize = this.file.size
this.fileType = source.type
this.fileReader = new FileReader()
this.fileReader.addEventListener('load', () => {
this.dataView = new DataView(this.fileReader.result)
})
this.fileReader.addEventListener('error', console.error)
this.fileReader.readAsArrayBuffer(this.file)
}
}
/**
* Read a Byte (offset) in Hexadecimal File
*
* @param {number} pos The offset for read - E.g. 0x22
* @return {number}
*/
readByte (pos) {
return this.dataView.getUint8(pos)
}
/**
* Read various Bytes (offsets) in Hexadecimal File
*
* @param {number} pos The offset for read - E.g. 0x22
* @param {number} nBytes Number of bytes to read
* @return {Array<number>}
*/
readBytes (pos, nBytes) {
const bytes = new Array(nBytes)
for (let i = 0; i < nBytes; i++) {
bytes[i] = this.readByte(pos + i)
}
return bytes
}
/**
* Write a Byte(s) to a offset in Hexadecimal File
*
* @param {number} pos The offset for write - E.g. 0x22
* @param {number} byte Byte to write
*/
writeByte (pos, byte) {
this.dataView.setUint8(pos, byte)
}
/**
* Save file with FileSaver.js
*/
save () {
let blob
try {
blob = new Blob([this.dataView], {
type: this.fileType
})
} catch (err) { // old browser, using BlobBuilder or try again
console.error(err)
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder
if (err.name === 'TypeError' && window.BlobBuilder) {
const bb = new BlobBuilder()
bb.append(this.dataView.buffer)
blob = bb.getBlob(this.fileType)
} else if (err.name === 'InvalidStateError') {
blob = new Blob([this.dataView.buffer], {
type: this.fileType
})
}
}
saveAs(blob, this.fileName)
}
}
export default HexFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment