Skip to content

Instantly share code, notes, and snippets.

@coreylight
Created April 12, 2022 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreylight/345293db424dd8c1de83854b300ab29b to your computer and use it in GitHub Desktop.
Save coreylight/345293db424dd8c1de83854b300ab29b to your computer and use it in GitHub Desktop.
JS client download data on the fly
export const downloadData = async (
fileName: string,
data: object | string
): Promise<void> => {
const stringData = typeof data === 'string' ? data : JSON.stringify(data);
try {
const dataBlob = new Blob([stringData], { type: 'text/json' });
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
link.parentNode?.removeChild(link);
} catch (err) {
console.error(err);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment