Reputation: 544
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)
Upvotes: 6
Views: 18246
Reputation: 50592
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:
Upvotes: 5
Reputation: 46647
There is no file I/O in javascript for security reasons. Your best bet is to expose this text file in your server code and make an ajax call for it from the javascript
Upvotes: 0
Reputation: 251
var fileRead = "Jason,Red,Tyrannosaurus\nZack,Black,Mastodon\nBilly,Blue,Triceratops\nTrini,Yellow,Griffin";
var lines = fileRead.split("\n");
for (var i in lines){
var pdata = lines[i].split(",");
jQuery("#ResultDiv").append("Name: " + pdata[0] + "<br/>Color: " + pdata[1] + "<br/>Avatar: " + pdata[2] + "<br/><br/>" );
}
Upvotes: -2
Reputation: 82564
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.
Upvotes: 6