如何用javascript操作本地文件

如题所述

操作文件主要是利用了Javascript中的FileSystemObject对象,直接上代码:

<html>
<head>
<script>
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2, ForAppending = 8;
function createFile(file){
   var tf = fso.CreateTextFile(file, true);
   tf.Close();
}
function readFileOnly(file){
   var ts = fso.OpenTextFile(file, ForReading);
   var s = ts.ReadAll();
   ts.Close();
   alert(s);
}
function readFileForWrite(file,content){
   var ts = fso.OpenTextFile(file, ForWriting);
   ts.Write(content);
   ts.Close();
}
function readFileForAppend(file,content){
   var ts = fso.OpenTextFile(file, ForAppending);
   ts.Write(content);
   ts.Close();
}
</script>
</head>
<body>
    <input type="button" onclick="createFile('d:\\test.txt');" value="创建文件"/><br>
    <input type="button" onclick="readFileOnly('d:\\test.txt');" value="读取文件"/><br>
    <input type="button" onclick="readFileForWrite('d:\\test.txt','write');" value="覆盖文件内容"/><br>
    <input type="button" onclick="readFileForAppend('d:\\test.txt','append');" value="追加到文件末尾"/>
</body>
</html>

文件的创建,读取和写入方法都有,可以参考。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-02-21
浏览器的沙盒原理不允许js写本地文件,如果你是用nodejs做为你的解释引擎就可以了
第2个回答  2018-03-16
浏览器环境中的javascript是不能够操作本地文件的。
nodejs中的javascript是可以操作本地文件的。详情请看nodejs的 文件系统(File system)官方文档。本回答被提问者采纳
第3个回答  2018-03-16
怎么操作,读还是写。
相似回答