[英]How to read and write from/into text file using javascript?
是否有人擁有使用javascript讀取/寫入文本文件的示例代碼
我嘗試過的操作就像創建一個iframe並從iframe中將文本文件加載到其中一樣,我讀取了內容並使用字符串操作進行了一些更改,並且我不知道如何寫回文本文件。 而且在瀏覽器上,此代碼不起作用。
我的text.txt文件包含第一行第二行第三行第四行
<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>
在IE中,可以使用ActiveXObject和HTA。 但是,建議這些僅在本地使用,而不在WEB中使用。 查看: http : //msdn.microsoft.com/en-us/library/ms536471%28v=vs.85%29.aspx
有關文件操作的更多信息: http : //msdn.microsoft.com/zh-cn/library/bstcxhf7%28v=vs.84%29.aspx
基本功能如下:
ActiveXObject定義:
fso=new ActiveXObject('Scripting.FileSystemObject');
讀取文件:
iStream=fso.OpenTextFile('filePath',1,false);
iStream.ReadAll();
/* or looped iStream.ReadLine() */
iStream.Close();
寫入文件:
oStream=fso.OpenTextFile('filePath',2,true);
oStream.WriteLine(/*your_data*/);// This usually is looped according to your data
oStream.Close();
fso
-object也可以在常規的HTM頁中使用,但是經常會要求您接受對ActiveXObject的使用。
如果您在談論本地文件系統,那么“ HTML5是否允許您從瀏覽器內部與本地客戶端文件進行交互”中涵蓋了您的選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.