Dynamically create a file with node.js and make it available for download

I create a text editor in Node.js where the user creates a file in a text box. When he finishes editing the file, he can click the β€œexport” button, which launches the jQuery function, which reads the text field and publishes the text on the Node.js server. The server should read the information and return the file. I would like not to create a file on the server and serve it, I would rather create a file on the fly with streams. I tried using the following, but this did not work:

exports.exportfile = function(req,res){ var Stream = require('stream') var stream = new Stream(); res.setHeader('Content-disposition', 'attachment; filename=try.txt'); res.setHeader('Content-type', 'text/plain'); stream.pipe = function(dest) { dest.write('Hello Dolly') } stream.pipe(res) } 

Does anyone have an idea on how to achieve this?

+4
source share
1 answer

I tested this on my server and it worked. This was from a GET call, but I do not understand why it will not work with POST.

 res.setHeader('Content-disposition', 'attachment; filename=theDocument.txt'); res.setHeader('Content-type', 'text/plain'); res.charset = 'UTF-8'; res.write("Hello, world"); res.end(); 
+5
source

Source: https://habr.com/ru/post/1499155/


All Articles