简体   繁体   中英

How to read and write from/into text file using javascript?

Do any one have a sample code of how to read and write from/into text file using javascript

What i tried is like created a iframe and load text file into it from iframe i read the content and using string operation make some changes, and i have no idea how to write back to text file. and also on ie browser this code is not working.

My text.txt file contain First line second Line Third Line Fourth Line

<html>

<head>
  <title></title>
</head>

<body>
<script language="JavaScript" type="text/javascript">
<!--


var srcFrame;

function loadOuter(doc) {
 srcFrame = document.getElementById("hiddenContent");
 srcFrame.src = doc;



 transferHTML();

}

function transferHTML(){
 srcContent='';
 if (srcFrame.contentDocument){
 alert("document");
  srcContent=srcFrame.contentDocument.getElementsByTagName("BODY")[0].innerHTML;
 }
 else if (srcFrame.contentWindow){
  alert("window");
  srcContent=srcFrame.contentWindow.document.body.innerHTML;
 }

srcContent.length;
alert(" before push "+srcContent);
var arrayText="Last Line";
var lines = srcContent.split('\n');
lines=lines.slice(0, -1);
lines.push(arrayText,"</pre>");
lines = lines.join('\n');
srcContent=lines;
alert(srcContent);
document.getElementById("outerDisplay").innerHTML = srcContent;
}

</script>

<INPUT TYPE="button" VALUE="Test.txt" onClick="loadOuter('Test.txt')" >

<div id="outerDisplay"></div>

<iframe  id="hiddenContent" width="200" height="200" style="position:absolute;visibility:hidden;" ></iframe>

</body>

</html>

In IE this is possible using ActiveXObject and HTA. These, however, are recommended to use local only, not in the WEB. Look at: http://msdn.microsoft.com/en-us/library/ms536471%28v=vs.85%29.aspx

More info for file operations: http://msdn.microsoft.com/en-us/library/bstcxhf7%28v=vs.84%29.aspx

Basic functions below:

ActiveXObject definition:

fso=new ActiveXObject('Scripting.FileSystemObject');

Reading file:

iStream=fso.OpenTextFile('filePath',1,false);
iStream.ReadAll();
/* or looped iStream.ReadLine() */
iStream.Close();

Writing file:

oStream=fso.OpenTextFile('filePath',2,true);
oStream.WriteLine(/*your_data*/);// This usually is looped according to your data
oStream.Close();

fso -object can also be used in regular HTM-page, but you're asked to accept use of the ActiveXObject very often.

如果您在谈论本地文件系统,那么“ HTML5是否允许您从浏览器内部与本地客户端文件进行交互”中涵盖了您的选项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM