Reading a Text File from Server using JavaScript

javascript
Published on April 22, 2020

A text file on a server can be read with Javascript by downloading the file with Fetch / XHR and parsing the server response as text.

Note that the file needs be on the same domain. If the file is on a different domain, then proper CORS response headers must be present.

The below sample code uses Fetch API to download the file. Alternatively XMLHttpRequest can also be used to download the file as well.

Sample Code

<button id="download-file">Display File</button>
<pre id="preview-text"></pre>
document.querySelector("#download-file").addEventListener('click', async function() {
	try {
		let text_data = await downloadFile();
		document.querySelector("#preview-text").textContent = text_data;
	}
	catch(e) {
		alert(e.message);
	}
});

async function downloadFile() {
	let response = await fetch("/sample.txt");
		
	if(response.status != 200) {
		throw new Error("Server Error");
	}
		
	// read response stream as text
	let text_data = await response.text();

	return text_data;
}
In this Tutorial