1,105,534 Community Members

javascript read a text file

Member Avatar
FALL3N
Junior Poster in Training
88 posts since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

I could probably/def read a text file with javascript by embedding some ruby in there but I want to know how to do it with javascript. My code follows:

<HTML>
<HEAD>
<TITLE>"Text File"</TITLE>
<SCRIPT LANGUAGE = JAVASCRIPT>

function handleFile() {
    var myFile = document.getElementById('txtF')
	var fileContents = System.IO.File.ReadAllLines(myFile);
	
	document.form1.textfield.value=fileContents;
}

</SCRIPT>

</HEAD>

<BODY>

<input type="file" id="aFile" name="txtF"/>

<form name="form1">
<input type="text" name="textfield" value="">
</form>

<input type="button" value="Read File" onclick="handleFile();">
<!-- <button onclick="loadTxtDoc('textfile.txt')">Click</button>  //-->

</BODY>
</HTML>

what am I doing wrong?

Member Avatar
ivan3510
Junior Poster
165 posts since Aug 2010
Reputation Points: 3 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

I don't think you can read the file with javascript (but nevermind).
Your mistake:

var myFile = document.getElementById('txtF')
//this means: ID="txtF", and you don't have it (you have name="txtF")
//so, you have to replace it (name) with ID (or add id='txtF')
Member Avatar
aidant
Newbie Poster
12 posts since Apr 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

use jquery:

$(".content").load("file.html");
Member Avatar
tawes01
Light Poster
37 posts since Oct 2010
Reputation Points: -2 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

It's much easier to read an XML file, but if you really want to read a text file, I've done it before. I used this tutorial/guide, and it was very helpful.

Member Avatar
FALL3N
Junior Poster in Training
88 posts since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

oh ok, I didn't realize javascript was not a simple language to use to read text files... like in regular Java, it is SO easy to read a text file. what is this other way to read xml files then?

Member Avatar
tawes01
Light Poster
37 posts since Oct 2010
Reputation Points: -2 [?]
Q&As Helped to Solve: 5 [?]
Skill Endorsements: 0 [?]
 
0
 

I'm not sure exactly how, but I know it's easier. It's still kind of complicated, though.
http://www.w3schools.com/xml/xml_parser.asp

Now, you should know that Javascript is not a file-manipulating language. In other words, it is not meant for, and is not really capable of (at least alone, without activex) reading external files. It can reference them, but not really access the content of those files and store it in a variable.

Member Avatar
Sogo7
Light Poster
41 posts since May 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 13 [?]
Skill Endorsements: 1 [?]
 
0
 

Yahoo Pipes has the ability to read the contents of file and assign them to a variable that can be invoked from client side javascript.

It's close cousin YQL also has 'storage pockets' 100kb in size that the contents of which can be manipulated by browser javascript in conjuntion with Yahoo Pipes.

However doing it this way is an ugly hack and should only be used as a last resort if the webhost does not support server side scripting. (it's not common but some don't believe it or not)

Member Avatar
FALL3N
Junior Poster in Training
88 posts since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

thanks! Yeah, I'll def check out YQL and Yahoo Pipes. And, thanks for that link about XML, I'll try that too.. I'll probably end up usingi a combo of these answers..

oh and Tawes, what do you mean that js can reference files, but not read them? cuz that might be enough..

Member Avatar
macgurl70
Junior Poster
129 posts since Jul 2010
Reputation Points: 9 [?]
Q&As Helped to Solve: 14 [?]
Skill Endorsements: 0 [?]
 
0
 

Here is an old (pre using JQuery) script that reads in a .csv file to make a table out of it - from a forum question a long long time ago. The XML route would be much easier to format and maintain in the long run.

It's similar to the tutorial - but uses the XMLHttpRequest to bring in the text. At least it gives another option to think about.

// JavaScript Document
// Thank you VERY much to Ben Nadel for this on his blog
// posted at 
//http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
	

if (window.XMLHttpRequest) {
		//for firefox, opera and safari browswers
		var txtFile = new XMLHttpRequest();
	}
	if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP.3.0 and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
  };
  
txtFile.open("GET","TestingOne.csv");
txtFile.send(false);

var allText = txtFile.responseText;

	
function clickyHere (){
	//var tar = document.getElementById('finalTable');
	var info = txtFile.responseText;
	var infoArray = [];
	infoArray = info.split(/,|,+\s|\s+,\n|\r/);
	var tableCount = info.split(/,|\$/g).length;
	var rowCount = info.split(/\r|[\r]/g).length;
	var endLine = info.split(/\$/g).length;
	var columnTry = tableCount/endLine;
	document.write("<table border='1' columns='"+columnTry+"'>");
	document.write("<tr>");
	var count;
	count = 0;
	for (i=0;i<infoArray.length;i++){
		x = infoArray[i];
		document.write("<td>"+x+"&nbsp;");
		if (count != columnTry){
			count ++;
			//document.write("</td>");
			}
		if (count >= columnTry){
			document.write("</tr><tr>");
			count = 0;
			}
	}					
			document.write("</tr></table>");
			
}

The Html code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="tableTest3.js"></script>
<title>Untitled Document</title>
</head>

<body>
<form id="tablebuild">
<input type="button" value="Click me" onclick="clickyHere();" />
</form>
<div id="finalTable"></div>
</body>
</html>

I attached the original text file, but I did convert it to a csv file.

Attachments TestingOne.txt (5.97KB)
Member Avatar
FALL3N
Junior Poster in Training
88 posts since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks so Much! that is exactly what I am trying to do! I am trying to make a list on my webpage based on a CSV file I get updated versions of every so often...

Only problem is, the 'FileSystemObjects' from Tawes do not seem to work properly on my Linux Ubuntu machine.


And Macgurl70, that code is great! Looks like it does exactly what I need the code to do... but the table (that is generated after pushing the button) is blank.. and I read the text file, it is DEFINITELY not blank... does this also not work on linux?

Member Avatar
FALL3N
Junior Poster in Training
88 posts since May 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

oh... wow, nvm.. I am very dumb :D all I had to do was change the name of the list file from, 'TestingOne.txt' to 'TestingOne.csv'...

Wow, sorry about that! I am kinda special I guess :\

Thanks again for the code!

Question Answered as of 2 Years Ago by tawes01, macgurl70, ivan3510 and 2 others
Member Avatar
lalazo
Newbie Poster
1 post since Oct 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

macgurl70,
I would change this
txtFile.send(false);
like so:
txtFile.send(null);

Member Avatar
L0st
Newbie Poster
2 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

This is great except that the CSV data will come out as unquoted so when i run something like indexOf(7) it cannot read strings.
what can you add to that RegEx so that the items are "quoted"

thanks.
Member Avatar
stbuchok
Posting Shark
957 posts since May 2011
Reputation Points: 123 [?]
Q&As Helped to Solve: 142 [?]
Skill Endorsements: 2 [?]
 
0
 

You can read local files using JavaScript (not supported in all browsers).

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Member Avatar
L0st
Newbie Poster
2 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

thanks stbuchok but the reason why i'm looking at this javascript solution is because i have to be compatible with IE 7.

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: