readFileAs*
Promise wrappers around FileReader.
| Function | Resolves with | Use for |
|---|---|---|
readFileAsArrayBuffer(blob) | ArrayBuffer | Binary processing |
readFileAsUint8Array(blob) | Uint8Array | Feeding checkEncoding / arrayBufferToString |
readFileAsText(blob, encoding?) | string | Text files; sniff the encoding first if it is unknown |
readFileAsDataURL(blob) | string | Image previews |
Example
js
import { readFileAsUint8Array, arrayBufferToString } from 'ranuts';
input.addEventListener('change', async (e) => {
const bytes = await readFileAsUint8Array(e.target.files[0]);
const text = arrayBufferToString(bytes); // encoding is sniffed, GBK/Big5 included
});Notes
- All three exits are wired —
onload,onerrorandonabort. Forgettingonabortis the classic way to leave a promise pending forever when the user cancels the picker. - Rejects with a clear error where
FileReaderdoes not exist (Node, some worker contexts). - Never
new TextDecoder().decode()a file of unknown origin — that assumes UTF-8 and turns GBK/Big5 into mojibake. UsearrayBufferToString, which sniffs first.