Download Generated Text as a File with JavaScript

JavaScript can download generated text without sending it to a server. Create a Blob with the correct MIME type, make a temporary object URL, click a download link, and revoke the URL after the browser has started the download.

Last updated: September 26, 2026.

function downloadText(text, filename = 'notes.txt') {
  const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');

  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();

  setTimeout(() => URL.revokeObjectURL(url), 0);
}

downloadText('First line\nSecond line\n', 'example.txt');

Blob URLs reference in-memory data and are scoped to the document’s origin. Revoking them releases the backing object when it is no longer needed.

Generate CSV carefully

For CSV, quote fields containing commas, quotes, or line breaks and double embedded quote characters. Join rows with a consistent line ending and use text/csv;charset=utf-8. Some spreadsheet workflows expect a UTF-8 BOM; add it only for a known consumer, because it becomes part of the file.

Control names and memory use

Sanitize suggested filenames: remove path separators and control characters, then provide a safe extension. A Blob keeps generated content in memory, so this approach is best for moderate files. Very large exports should stream from a server or use a browser streaming API designed for the target environment.

MDN’s blob URL reference explains download use and object-URL cleanup. Do not revoke the URL before the click has been processed.

Understand browser boundaries

The download attribute suggests a filename but does not bypass browser security or user preferences. It works reliably for same-origin and generated Blob URLs. If the user only needs a short value, the existing clipboard guide may provide a better interaction than creating a file.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov