Skip to content

Commit

Permalink
Merge pull request #13 from observerly/feat/utilities/readBlockAsArra…
Browse files Browse the repository at this point in the history
…yBuffer

feat: Added readBlockAsArrayBuffer() in utilities module.
  • Loading branch information
michealroberts authored Jan 14, 2022
2 parents 0b8af45 + 54fb921 commit 82bb163
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ export { getFITSHeaders, parseFITSHeaderRow } from './header'
export { getFITSBlocks } from './fits'

// Utilities
export { getExcessByteSize } from './utilities'
export { getExcessByteSize, readBlockAsArrayBuffer } from './utilities'
6 changes: 6 additions & 0 deletions src/types/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ export interface FITSBlock {
*
*/
buffer: string | ArrayBuffer
/**
*
* The ArrayBuffer as a raw parsed string
*
*/
s?: string
/**
*
*
Expand Down
2 changes: 2 additions & 0 deletions src/utilities/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export { getExcessByteSize } from './getExcessByteSize'

export { readBlockAsArrayBuffer } from './readBlockAsArrayBuffer'
35 changes: 35 additions & 0 deletions src/utilities/readBlockAsArrayBuffer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
*
* readBlockAsArrayBuffer()
*
* @description asynchronously reads a file slice as an ArrayBuffer
* and onloadend will pass the ArrayBuffer result to a callback function.
*
* @param block represents a File or File.slice
* @param callback function callback to be called onloadend passing
* @returns a Promise which resolves the callback of the callback function provided
*/
export const readBlockAsArrayBuffer = async (
block: Blob,
callback: (result: ArrayBuffer) => { s: string; end: boolean; parsed: boolean }
): Promise<{ s: string; end: boolean; parsed: boolean }> => {
return new Promise((resolve, reject) => {
const reader = new FileReader()

reader.onloadend = (e: ProgressEvent<FileReader>) => {
if (e.target?.result && e.target.result instanceof ArrayBuffer) {
resolve(callback(e.target.result))
}

resolve({
s: '',
end: false,
parsed: false
})
}

reader.onerror = reject

reader.readAsArrayBuffer(block)
})
}

0 comments on commit 82bb163

Please sign in to comment.