Last active
March 4, 2017 20:44
-
-
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
This file contains hidden or 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
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