)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Save a Text File with JavaScript

  1. function saveFile(text, name = 'file', mime = 'text/plain') {
  2.   const blob = new Blob([
  3.     text
  4.   ], { type: mime });
  5.   const a = document.createElement('a')
  6.  
  7.   a.download = name + '.txt'
  8.   a.href = window.URL.createObjectURL(blob)
  9.   a.click();
  10. }
  11.  
  12. // hacky way to create the button and have it call `saveFile`
  13. // when clicked
  14. document.body.appendChild(
  15.   Object.assign(
  16.     document.createElement`button`,
  17.   { innerText: 'click me' })
  18. ).onclick = () => saveFile('Hello there')
snippet.zone ~ 2021-24 /// {s/z}