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.
var text={"hello.txt":"Hello World!","bye.txt":"Goodbye Cruel World!"};
app.get('/files/:name',function(req,res){
res.set({"Content-Disposition":"attachment; filename=\"req.params.name\""});
res.send(text[req.params.name]);
});
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 to text/html
. Here is a good reference to Internet Media Types and MIME types.
Thanks for the help guys, this is what i ended up with:
@aaron, is there a way for disposition to work in all browsers?
res.setHeader('Content-disposition', 'attachment; filename=theDocument.txt');
res.setHeader('Content-type', 'text/plain');
res.charset = 'UTF-8';
res.write("Hello, world");
res.end();
this is working for me !
var text="hello world";
res.setHeader('Content-type', "application/octet-stream");
res.setHeader('Content-disposition', 'attachment; filename=file.txt');
res.send(text);
Try this:
router.get('/download', (req, res) => {
var text = 'Hello world!'
res.attachment('filename.txt')
res.type('txt')
res.send(text)
})