编辑文件-纯js
Edit file - pure js
如何在纯 js(无节点)中编辑文件?
我得到一个带有输入字段的文件,我这样阅读它的文本:
var fileReader = new FileReader();
fileReader.readAsText(file);
fileReader.onload = function () {
alert(this.result);
}
所以,非常简单。我试图在网上查看如何使用 fileWriter 但没有成功。
我只需要编辑该文件中的文本并保存它,我该怎么做?
你不能在浏览器中写文件,你必须使用节点。
可以读入文本文件中的数据,在客户端修改JavaScript(无Node),然后输出并重新保存。不过,它确实需要用户交互。
最初取自this Whosebug question
(function () {
var textFile = null;
function makeTextFile(text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
}
var create = document.getElementById('create');
var textbox = document.getElementById('textbox');
//create a click event listener
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.setAttribute('download', 'info.txt');
//make the text file
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
//wait for the link to be rendered and then initiate a click to download the file
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
})();
如何在纯 js(无节点)中编辑文件? 我得到一个带有输入字段的文件,我这样阅读它的文本:
var fileReader = new FileReader();
fileReader.readAsText(file);
fileReader.onload = function () {
alert(this.result);
}
所以,非常简单。我试图在网上查看如何使用 fileWriter 但没有成功。 我只需要编辑该文件中的文本并保存它,我该怎么做?
你不能在浏览器中写文件,你必须使用节点。
可以读入文本文件中的数据,在客户端修改JavaScript(无Node),然后输出并重新保存。不过,它确实需要用户交互。
最初取自this Whosebug question
(function () {
var textFile = null;
function makeTextFile(text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
}
var create = document.getElementById('create');
var textbox = document.getElementById('textbox');
//create a click event listener
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.setAttribute('download', 'info.txt');
//make the text file
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
//wait for the link to be rendered and then initiate a click to download the file
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
})();