To create a file in JavaScript for browser-side scripting, you can use the Blob
object and the URL.createObjectURL()
method. Here's an example code block that creates a file with some text content:
index.tsx606 chars21 lines
This code creates a Blob
object with the text content and specifies its MIME type (in this case, plain text). Then it generates a temporary URL for the Blob
using URL.createObjectURL()
. Next, it creates a new anchor element (<a>
) and sets its href
attribute to the temporary URL and its download
attribute to the desired filename. Finally, it appends the anchor element to the DOM, clicks on it programmatically, and releases the temporary URL resource using URL.revokeObjectURL()
. The end result is that the browser prompts the user to download a file named file.txt
with the content "Hello, World!".
gistlibby LogSnag