unicorn/prefer-blob-reading-methods
Require blob.text() and blob.arrayBuffer() instead of a FileReader
A FileReader delivers its result in a load event, so you end up writing a handler for it, another for error, and often a promise around both. blob.text() and blob.arrayBuffer() return a promise that you can await. A File is a Blob, so it has them too.
The rule reports any call to a method named readAsText or readAsArrayBuffer with one argument.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-blob-reading-methods" = "error" # or "warn"Examples#
example.js1 problem
function readText(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => resolve(reader.result));
reader.addEventListener("error", () => reject(reader.error));
reader.readAsTextPrefer Blob#text() over FileReader#readAsText(blob).(file);
});
}example.js1 problem
reader.readAsArrayBufferPrefer Blob#arrayBuffer() over FileReader#readAsArrayBuffer(blob).(file);example.jsNo problems
function readText(file) {
return file.text();
}
const bytes = await file.arrayBuffer();blob.text() always decodes as UTF-8. A call that passes an encoding has no replacement, so it isn't reported:
example.jsNo problems
reader.readAsText(file, "shift-jis");