Read text file and display in html using javascript
In this article, you are going to learn how to read the content of a text file and display it in an HTML webpage using JavaScript.
We'll explore two methods to achieve this: the FileReader API and the fetch API.
Method 1: Using the FileReader API #
The FileReader API allows us to read files asynchronously in the browser. We can create an HTML input element to select a text file and then use JavaScript to read its content.
<input type="file" id="fileInput">
<pre id="output"></pre>
<script>
document.getElementById('fileInput').addEventListener('change', function () {
const fileInput = document.getElementById('fileInput');
const outputDiv = document.getElementById('output');
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const fileContent = e.target.result;
outputDiv.textContent = fileContent;
};
reader.readAsText(file);
});
</script>
Explanation of the above example:
- We create an input element to select a file and a <pre> element to display the file's content.
- We add an event listener to the input element that triggers when a file is selected.
- Inside the event listener, we get the selected file and create a FileReader object.
- The onload event of the FileReader object is used to handle the file reading process.
- We read the file as text using readAsText and display the content in the <pre> element.
Method 2: Read text file using the fetch API #
The fetch API allows us to make network requests, including loading local files. We can fetch the content of a text file and display it in HTML.
<pre id="output"></pre>
<script>
fetch('https://app.3schools.in/css/styles.css')
.then(response => response.text())
.then(data => {
const outputDiv = document.getElementById('output');
outputDiv.textContent = data;
})
.catch(error => {
console.error('Error:', error);
});
</script>
Explanation:
- We create a <pre> element to display the file content.
- We use the fetch function to request the css file ('https://app.3schools.in/css/styles.css' should be replaced with your text file's path).
- We use .then() to handle the response and extract the text content.
- The content is then displayed in the output <pre>, and errors are caught and logged.
Conclusion #
In this article, you've learned two methods to read the content of a text file and display it in an HTML webpage using JavaScript.
Whether you choose the FileReader API or the fetch API depends on your specific use case. Both methods provide a convenient way to work with text files in web applications.
