Last active
November 26, 2015 05:21
-
-
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+.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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