Skip to content Skip to sidebar Skip to footer

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 T

Solution 1:

Here's an example using XMLHttpRequest:

var xmlhttp;
xmlhttp=newXMLHttpRequest();
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.

Solution 2:

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)

Solution 3:

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

Solution 4:

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/>" );
}

Post a Comment for "Read External File With Javascript"