2013-04-25 84 views
4

我得到了一个小脚本,在每4个字符后分割'var foo'内的文本。它工作正常。 但我的实际数据是在一个文本文件中说'a.txt'。如何在'var foo'中获取整个文件的文本。并将分割输出写入另一个文本文件?如何阅读JavaScript变量中的文件内容?

var foo = "this is sample text !!!"; 
var arr = []; 
for (var i = 0; i < foo.length; i++) { 
    if (i % 4 == 0 && i != 0) 
     arr.push(foo.substring(i - 4, i)); 
    if (i == foo.length - 1) 
     arr.push(foo.substring(i - (i % 4), i+1));   
} 
document.write(arr); 
console.log(arr); 
+0

可能重复[如何读取和写入文件使用JavaScript](http://stackoverflow.com/questions/585234/how-to-read-and-write-into-file-using-javascript) – Chase 2013-04-25 12:22:53

+0

我在问题标题,说明和提供的代码中看不到任何重要的关系。请尝试在浏览器中使用JS或服务器开发的本机应用程序来解释您的问题的上下文,例如您试图在何处执行此代码。 – saurav 2016-10-14 16:50:13

回答

3

要获取文件的内容,您需要使用输入标签选择文件。

<!DOCTYPE html> 
<head> 
    <meta charset="UTF-8"> 
</head> 
<body> 
    <input id="input" type="file" accept="text/plain"> 
    <script src="script.js"></script> 
</body> 

读取文件内容的好时机是在change事件中。

const input = document.querySelector("#input"); 

input.addEventListener("change",() => { 
    const file = input.files.item(0); 
}); 

要将文件的内容作为字符串读取,您需要将其转换。

function fileToText(file, callback) { 
    const reader = new FileReader(); 
    reader.readAsText(file); 
    reader.onload =() => { 
    callback(reader.result); 
    }; 
} 

作为字符串的文件内容将可用于回调函数。您可以创建链接并使用click事件将字符串下载到文本文件中。

function save(content, fileName, mime) { 
    const blob = new Blob([content], { 
    tipe: mime 
    }); 
    const url = URL.createObjectURL(blob); 
    const a = document.createElement("a"); 
    a.href = url; 
    a.download = fileName; 
    a.click(); 
} 

下面是完整的代码

const input = document.querySelector("#input"); 
 

 
input.addEventListener("change",() => { 
 
    const file = input.files.item(0); 
 
    fileToText(file, (text) => { 
 
    save(text, "fileName.txt", "text/plain"); 
 
    }); 
 
}); 
 

 
function fileToText(file, callback) { 
 
    const reader = new FileReader(); 
 
    reader.readAsText(file); 
 
    reader.onload =() => { 
 
    callback(reader.result); 
 
    }; 
 
} 
 

 
function save(content, fileName, mime) { 
 
    const blob = new Blob([content], { 
 
    tipe: mime 
 
    }); 
 
    const url = URL.createObjectURL(blob); 
 
    const a = document.createElement("a"); 
 
    a.href = url; 
 
    a.download = fileName; 
 
    a.click(); 
 
}
<!DOCTYPE html> 
 

 
<head> 
 
    <meta charset="UTF-8"> 
 
</head> 
 

 
<body> 
 
    <input id="input" type="file" accept="text/plain"> 
 
    <script src="script.js"></script> 
 
</body>

您可以在此处详细了解在JavaScript处理文件:https://www.html5rocks.com/en/tutorials/file/dndfiles/