read.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. export const readFileAs = (file: File, isBinary = false) => {
  7. const fileReader = new FileReader()
  8. return new Promise<string | Uint8Array>((resolve, reject) => {
  9. fileReader.onerror = () => {
  10. fileReader.abort()
  11. reject(new DOMException('Error parsing file.'))
  12. }
  13. fileReader.onload = () => {
  14. resolve(isBinary ? new Uint8Array(fileReader.result as ArrayBuffer) : fileReader.result as string)
  15. }
  16. if (isBinary) {
  17. fileReader.readAsArrayBuffer(file)
  18. } else {
  19. fileReader.readAsText(file)
  20. }
  21. })
  22. }
  23. export function readFileAsText(file: File) {
  24. return readFileAs(file, false) as Promise<string>
  25. }
  26. export function readFileAsBuffer(file: File) {
  27. return readFileAs(file, true) as Promise<Uint8Array>
  28. }
  29. export async function readUrlAs(url: string, isBinary: boolean) {
  30. const response = await fetch(url);
  31. return isBinary ? new Uint8Array(await response.arrayBuffer()) : await response.text();
  32. }
  33. export function readUrlAsText(url: string) {
  34. return readUrlAs(url, false) as Promise<string>
  35. }
  36. export function readUrlAsBuffer(url: string) {
  37. return readUrlAs(url, true) as Promise<Uint8Array>
  38. }