Skip to content

Instantly share code, notes, and snippets.

@iansinnott
Last active November 26, 2015 05:21
Show Gist options
  • Save iansinnott/59f26abab792fff27db8 to your computer and use it in GitHub Desktop.
Save iansinnott/59f26abab792fff27db8 to your computer and use it in GitHub Desktop.
Asynchronously read the contents of a user-uploaded file. A Promise wrapper around the FileReader API. IE 10+.
/**
* Asynchronously read a file. This is simply a wrapper around the FileReader
* API, which is not great.
* @param {File|Blob} file to read
* @return {Promise}
*/
export const readFile = file => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
if (!(file instanceof Blob)) {
const err = new Error('file must be an instance of File or Blob.');
return reject(err);
}
reader.onerror = reject;
reader.onabort = reject;
reader.onloadend = contents => resolve(reader.result, file);
return reader.readAsText(file);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment