.txt
Example
const blob = new Blob([text]);
location.href = URL.createObjectURL(blob);const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = Object.assign(document.createElement('a'), { href: url, download: 'notes.txt' });
a.click();
URL.revokeObjectURL(url);A typed UTF-8 blob and a link with download save a named file instead of opening it, and the URL is freed after.
Common mistakes
- Text turning into garbled characters because the file or server uses the wrong encoding.
- Mixing Windows and Unix line endings, which shows up as diffs on every line.
Key points
- The
Blobtype is 'text/plain;charset=utf-8' so non-English text keeps its characters. - The object URL is released with
URL.revokeObjectURL()after the download starts. - Servers send
.txtfiles with 'text/plain; charset=utf-8' as theContent-Type.
Interview questions
What encoding should a .txt file use?
Use UTF-8. It covers every language and is the default for most editors, servers and tools.
What is the difference between LF and CRLF line endings?
Unix and macOS use LF, while Windows tools often use CRLF. Pick one per project, usually LF, and enforce it in the editor and Git.