Skip to content

Instantly share code, notes, and snippets.

@gregzanch
Created January 22, 2021 23:41
Show Gist options
  • Save gregzanch/7ad674504782fb4073dcabc9844dea92 to your computer and use it in GitHub Desktop.
Save gregzanch/7ad674504782fb4073dcabc9844dea92 to your computer and use it in GitHub Desktop.
Read a text file in javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input type="file" id="fileinput"></input>
<script src="index.js"></script>
</body>
</html>
console.log("hi");
const fileinput = document.getElementById("fileinput");
let filecontents;
fileinput.addEventListener("change", (e) => {
console.log(e.target.files);
const reader = new FileReader();
reader.addEventListener("loadend", (loadEndEvent) => {
if (reader.DONE) {
filecontents = reader.result;
console.log(filecontents);
}
});
reader.readAsText(e.target.files[0]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment