如何在文件中写入 JavaScript 然后下载文件?

How can I write in a document with JavaScript and then download the document?

如何在 JSON 或带有 JavaScript 的 TXT 文件中写入示例。我在文件中写入后如何下载它。类似于 python

中的操作
File = open("FileToWriteIn.txt", "wb")
File.write("Hello")
File.close()
# Then I want to download the file which in this case would be FileToWriteIn.txt but I want to
# do this with JavaScript

谢谢。

有关文件保存,请查看 FileSaver.js,它提供了一种保存文件的简单方法。写入文本文件将如下所示:

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");

这将自动打开下载对话框。

您可以创建 Blob。下面是一个示例,我已将此代码段的结果放入 iFrame 中,但如果您想下载,可以使用 window.open 代替。

//create blob
const blob = 
  new Blob([JSON.stringify(
  {
    hello: 'world'
  })], 
  {type : 'application/json'});
  
//turn into a URL for download or view etc.
const url = URL.createObjectURL(blob);

//for testing, lets put in an iframe
const frame = document.createElement('iframe');
frame.setAttribute('src',url);
document.body.appendChild(frame);