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

How can I write for example in a JSON or TXT file with JavaScript. After I write in the file how can I download it. Similar to doing this in 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

Thanks.

Answer

For file saving take a look at FileSaver.js which provides a simple approach to save files. Writing to a text file will then look like this:

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

This will automatically open the download dialogue.