简体   繁体   English

如何使用纯 JavaScript 和 append 创建一个文本文件?

[英]How do I create a text file using pure JavaScript, then append to it?

I want to append data into a txt file.我想将 append 数据转换成 txt 文件。 I looked at other questions, and all of the answers were only supported in IE.我查看了其他问题,所有答案都仅在 IE 中支持。 This is what I have so far (I'm a complete JavaScript rookie, so I don't know anything about doing this kind of stuff):这是我到目前为止所拥有的(我是一个完整的JavaScript菜鸟,所以我对做这种事情一无所知):

var word = "word"; var word = "单词"; //Missing Code //缺少代码

What is the pure JavaScript code here????这里纯JavaScript代码是什么????

I found old answer here我在这里找到了旧答案

const createTextFile = (fileNmae, text) => {
  const element = document.createElement('a');

  element.setAttribute(
    'href',
    'data:text/plain;charset=utf-8,' + encodeURIComponent(text),
  );
  element.setAttribute('download', fileNmae);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
};

createTextFile('test.txt', 'word');


let data = "some"
let file = new Blob([data], {type: "txt"})

// Appending to the file can be mimiced this way
data = data+"Text"
file = new Blob([data], {type: "txt"})

// To Download this file
let a = document.createElement("a"), url = URL.createObjectURL(file);
a.href = url;
a.download = file;
document.body.appendChild(a);
a.click()
setTimeout(function() {
  document.body.removeChild(a);
}, 0);

Hope this can help希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM