I have an external textfile of variable length named profiles.txt with information in the following format:
Jason/Red/Tyrannosaurus
Zack/Black/Mastodon
Billy/Blue/Triceratops
Trini/Yellow/Griffin
(etc)
How can I read through the file using JavaScript to output the following HTML:
Name: Jason<br>
Color: Red<br>
Avatar: Tyrannosaurus<br>
<br>
Name: Zack<br>
Color: Black<br>
Avatar: Mastodon<br>
<br>
(etc)
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text.
Web browsers (and JavaScript) can only access local files with user permission. To standardize file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.
Here's an example using XMLHttpRequest:
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET', "test.txt", false);
xmlhttp.send();
document.write(xmlhttp.responseText.split('\r\n').map(function (i) {return i.replace(/(.+),(.+),(.+)/g, 'Name: $1<br>Color: $2<br>Avatar: $3<br>')} ).join('<br/>'));
Array.map needs to be shim in IE8 and below. Also, IE uses new ActiveXObject("Msxml2.XMLHTTP")
This is a very slimmed down example. I'm using asyc false which is bad and document.write which is bad. But I just wanted to demonstrate getting the file and parsing the input.
ONLY APPLIES IF THE FILE IS NOT ALREADY ON THE SERVER (not specified in question)
Without posting the file to the server or pasting the file's contents into a textbox, there is currently no way for javascript to interact directly with the file system.
Also for security reasons, javascript may not, by itself, look at the contents of a file that has been selected using a file-type input.
So, your options are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With