Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a text file in node.js from a string and stream it in response

  1. I am using express.js

  2. I have a string "Hello world!"

  3. I want a user to click on

    <a href=/download>Download</a> 
  4. The user should get Hello.txt download with the text in it, NOT open a tab with the text.

  5. 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!

like image 906
user1323136 Avatar asked Feb 22 '14 05:02

user1323136


People also ask

How do I write a stream file in node JS?

To write to a file using streams, you need to create a new writable stream. You can then write data to the stream at intervals, all at once, or according to data availability from a server or other process, then close the stream for good once all the data packets have been written.

How do I stream data in node JS?

Chaining the Streams Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations. Now we'll use piping and chaining to first compress a file and then decompress the same. Verify the Output.

How do I create a read stream in node?

createReadStream() Method. The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it.


1 Answers

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.

like image 62
tsturzl Avatar answered Oct 06 '22 07:10

tsturzl