generate file to download in javascript

To generate a file for download in JavaScript, you can create a Blob object and use it to create a download link.

Here's an example:

index.tsx
function downloadFile(data, filename) {
    // Create a Blob object from the data
    const blob = new Blob([data]);

    // Create a download link
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename;

    // Append the link to the document and click it
    document.body.appendChild(link);
    link.click();

    // Clean up
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
}
467 chars
18 lines

In this example, the downloadFile function takes two arguments: data (the contents of the file) and filename (the name of the file to be downloaded). First, it creates a Blob object from the data. Then, it creates a download link by creating a new <a> element, setting its href attribute to the URL of the Blob object, and setting its download attribute to the desired filename. It appends the link to the document, triggers a click event on it, and finally removes the link and revokes the Blob URL to clean up.

You can use this downloadFile function to generate and download files by calling it with the desired data and filename.

index.tsx
const data = 'Hello, world!';
const filename = 'example.txt';
downloadFile(data, filename);
92 chars
4 lines

Note that the download attribute is not supported in some older browsers. In those cases, the file will open in a new browser tab instead of being downloaded.

related categories

gistlibby LogSnag