Reading a File in Plain Javascript (not! in node.js)
Reading a file in node.js is fairly easy and code to do it is easy to get by on the web. But doing it on the browser in a modern way, with async/await and returning an actual result, is not so much. Most of the time, you get only a console.logout() and that's it!
So I'm giving here a complete example of a readFile function that returns the contents of a local file. I have not found a way to get a file other than through an input of type "file" in the html page. It could have got some uses, but one must do without it!
It's also a nice and complete example of how to build a simple async function with a promise you build inside with something other than a timeout. All the best if it helps someone somewhere especially if this is you!
// returns the content of a file as text
const readFile = async (file) => {
const prom = new Promise((resolve, reject) => {
const frd = new FileReader();
frd.onload = (evt) => {
resolve(frd.result);
}
frd.readAsText(file);
});
const text = await prom;
return text;
};
// and here is a simple demo, to put soewhere in your code
// somewhere in your html: <input type="file" id="file"/>
document.getElementById("file").addEventListener("change", see);
async function see(event) {
const file = event.target.files[0];
if (file) {
const contents = await readFile(file);
const escapeHTML = (str) => new Option(str).innerHTML;
const sanitized = escapeHTML(contents);
console.log("sanitized", sanitized);
event.target.insertAdjacentHTML('afterend',
`<hr><h4>{file.name}</h4><pre>${sanitized}</pre><hr>`
);
}
}
And you can test it below!!!
Aucun commentaire:
Enregistrer un commentaire