I am using express.js
I have a string "Hello world!"
I want a user to click on
<a href=/download>Download</a>
The user should get Hello.txt download with the text in it, NOT open a tab with the text.
I have looked around for ways to achieve this, I am guessing it has something to do with creating readstreams from buffer and piping to response, but I most of the examples dealt with reading actual files from disk, I don't want to read from disk, i just want to respond with a file created from a string.
Thanks!
Thanks for the help guys, this is what i ended up with: @aaron, is there a way for disposition to work in all browsers?
this is working for me !
I think I understand what you're trying to do. You want to send a .txt file to the client without actually creating a file on disc.
This is actually pretty basic, and extremely easy. All you have to do is set your MIME type in the header, however most browsers don't download .txt files by default. They just open and display the contents.
As a future note, you can send any data that's stored as a variable. If you have a buffer loaded with an image, for example, you can send that the same way by just changing the
Content-Type
, otherwise the browser has no idea what data you're sending, and express I believe sets the default type totext/html
. Here is a good reference to Internet Media Types and MIME types.Try this: