Javascript Equivalent to file_get_contents("filename.html")

This Javascript function is performs the equivalent of the PHP function file_get_contents(). It returns the data file into an element Id, or a variable.

Also see Dynamically Load Content Without AJAX for an alternate method of loading data into a variable.


function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        document.getElementById("inbox").innerHTML = data;
    });
}

// or load into a variable

function get(filename) {
	fetch(filename).then((resp) => resp.text()).then(function(data) {
		temp = data;
	});
}

// or return it like the php file_get_contents

function get(filename) {
	fetch(filename).then((resp) => resp.text()).then(function(data) {
		return data;
	});
}

Example:

This example returns the contents of textTest.txt into the div element with id "elementID"

Javascript: 
document.getElementById("elementID").innerHTML = file_get_contents("textTest.txt");