create a file in javascript

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.tsx
// text content to be written in the file
const fileContent = 'Hello, World!';

// create a blob with the text content and specify the MIME type
const blob = new Blob([fileContent], { type: 'text/plain' });

// create a temporary URL for the blob object
const url = URL.createObjectURL(blob);

// create a new anchor element for downloading the file
const link = document.createElement('a');
link.href = url;
link.download = 'file.txt';

// append the anchor element to the DOM and click on it
document.body.appendChild(link);
link.click();

// release the temporary URL resource
URL.revokeObjectURL(url);
606 chars
21 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