我有一个 HTML 文件,它使用 Javascript 通过 ActiveXObject 对 .txt 文件执行文件 I/O 操作(仅适用于 Windows OS 上的 Internet Explorer)。
HTML页面上有一个文本输入框,还有一个按钮。该按钮调用一个函数 onclick
以将输入的文本写入 .txt 文件的末尾。HTML页面上还有一个textarea,将.txt文件修改后的内容复制粘贴到其中。到目前为止,所有这些都在工作......
所以,我想用 Javascript 从我的 HTML 页面中将制表符和换行符插入到 .txt 文件中。我正在使用这一行将 .txt 文件内容复制到 textarea 中,并在变量中初始化:
var newText = oldText + "\n" + document.getElementById("userInput").value;
当然,转义字符 \n
适用于 HTML 页面,而不适用于 .txt 文件......
那么如何将新行和制表符编码为 .txt 文件的可解析格式?我曾尝试 对此处找到的 值和 此处找到的 值使用该
escape()
方法 ,但没有运气。
到目前为止,这是我的代码:
ANSI
ASCII
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
</head>
<body>
<p>
Enter some text here:
<input type = "text" id = "userInput" />
</p>
<input type = "button" value = "submit" onclick = "main();" />
<br />
<hr />
<br /><br /><br />
<textarea id = "textHere" rows = 25 cols = 150></textarea>
<script type = "text/javascript">
// executes all code from this function to prevent global variables
function main()
{
var filePath = getThisFilePath();
var fileText = readFile(filePath);
writeFile(filePath, fileText);
} // end of function main
function getThisFilePath()
{
var path = document.location.pathname;
// getting rid of the first forward-slash, and ending at the last forward-slash to get rid of file-name
var correctPath = path.substr(1, path.lastIndexOf("/") );
var fixedPath = correctPath.replace(/%20/gi, " "); // replacing all space entities
return fixedPath;
} // end of function getThisFilePath
function readFile(folder)
{
var fso = "";
var ots = "";
var oldText = "";
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "read" mode (1)
ots = fso.OpenTextFile(folder + "writeToText.txt", 1, true);
oldText = ots.ReadAll();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
return oldText;
} // end of function readFile
function writeFile(folder, oldText)
{
var fso = "";
var ots = "";
var newText = oldText + "\n" + document.getElementById("userInput").value;
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "write" mode (2)
ots = fso.OpenTextFile(folder + "writeToText.txt", 2, true);
ots.Write(newText);
ots.Close();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
setText(newText); // with the function below
} // end of function writeFile
// called from the function writeFile
function setText(textFile)
{
document.getElementById("textHere").value = textFile;
} // end of function setText
</script> <!-- end of javascript -->
</body>
</html>