Henry Yun
Henry Yun

Reputation: 544

read external file with Javascript

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

Answers (4)

Chris Baker
Chris Baker

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:

  • Upload the file to the server using AJAX-style form post, return the contents (jQuery plugin for AJAX file uploads)
  • Submit the file via normal form postback, when the page is reloaded you can pass the contents along to javascript with JSON written to the output
  • Copy/paste the data into a textarea, use an onKeyUp event to detect entry of data (or add a "Process" button) to read the textarea contents and go from there (sample)

Upvotes: 5

jbabey
jbabey

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

Dave.Sol
Dave.Sol

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

Joe
Joe

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

Related Questions