Skip to content

Instantly share code, notes, and snippets.

@wlib
Last active March 4, 2017 20:44
Show Gist options
  • Save wlib/a9cf478f24a0297af9d291cf7544c477 to your computer and use it in GitHub Desktop.
Save wlib/a9cf478f24a0297af9d291cf7544c477 to your computer and use it in GitHub Desktop.
Load local files from disk and return blobs, or read them as text, uses promises
function loadFile() {
const input = document.createElement("input");
input.type = "file";
input.click();
return new Promise(function(resolve, reject) {
input.onchange = function() {
resolve( input.files[0] );
};
});
}
function readFile(blob, readAs="readAsText") {
const reader = new FileReader();
reader[readAs](blob);
return new Promise(function(resolve, reject) {
reader.onloadend = function() {
resolve( reader.result );
};
});
}
// Wrapper
function openFile() {
return loadFile().then(readFile);
}
// Example
openFile().then(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment