How do I load the contents of a text file into a javascript variable?

Javascript

Javascript Problem Overview


I have a text file in the root of my web app http://localhost/foo.txt and I'd like to load it into a variable in javascript.. in groovy I would do this:

def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;

How can I get a similar result in javascript?

Javascript Solutions


Solution 1 - Javascript

XMLHttpRequest, i.e. AJAX, without the XML.

The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();

Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.

One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.

Solution 2 - Javascript

here is how I did it in jquery:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});

Solution 3 - Javascript

Update 2019: Using Fetch:

fetch('http://localhost/foo.txt')
  .then(response => response.text())
  .then((data) => {
    console.log(data)
  })

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Solution 4 - Javascript

If you only want a constant string from the text file, you could include it as JavaScript:

// This becomes the content of your foo.txt file
let text = `
My test text goes here!
`;

<script src="foo.txt"></script>
<script>
  console.log(text);
</script>

The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

Solution 5 - Javascript

Update 2020: Using Fetch with async/await

const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);

Note that await can only be used in an async function. A longer example might be

async function loadFileAndPrintToConsole(url) {
  try {
    const response = await fetch(url);
    const data = await response.text();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');

Solution 6 - Javascript

This should work in almost all browsers:

var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
	console.log(xhr.responseText);
}
xhr.send();

Additionally, there's the new Fetch API:

fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )

Solution 7 - Javascript

One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really "load a file" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is

    client.onreadystatechange = function() {

and in danb's case, it is

 function(data) {

This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.

Solution 8 - Javascript

When working with jQuery, instead of using jQuery.get, e.g.

jQuery.get("foo.txt", undefined, function(data) {
    alert(data);
}, "html").done(function() {
    alert("second success");
}).fail(function(jqXHR, textStatus) {
	alert(textStatus);
}).always(function() {
    alert("finished");
});

you could use .load which gives you a much more condensed form:

$("#myelement").load("foo.txt");

.load gives you also the option to load partial pages which can come in handy, see api.jquery.com/load/.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanbView Question on Stackoverflow
Solution 1 - JavascriptEdward Z. YangView Answer on Stackoverflow
Solution 2 - JavascriptdanbView Answer on Stackoverflow
Solution 3 - JavascriptVicView Answer on Stackoverflow
Solution 4 - JavascriptErik UggeldahlView Answer on Stackoverflow
Solution 5 - JavascriptgmanView Answer on Stackoverflow
Solution 6 - Javascript12Me21View Answer on Stackoverflow
Solution 7 - JavascriptatmelinoView Answer on Stackoverflow
Solution 8 - JavascriptyvesonlineView Answer on Stackoverflow