Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js: how to download stream as a file?

My story is as follows: a user uploads a txt file to an express.js server, where the text file is transformed to a pdf file; the pdf file can be streamed back to the browser via request.pipe. I can get the stream on the user side, but how to let the browser download the stream as a pdf file?

like image 467
象嘉道 Avatar asked Oct 04 '14 02:10

象嘉道


People also ask

How do I download files from stream?

In this case, I think you need a mediator file handler on your application which reads the file contents from the web service and write back the file contents in the response stream. Right click on your project/website, select "Add new Item-> Generic Handler", give a name to your handler and click add. Now you have ".

How do I download a file using Express JS?

Step 1: create an “app. js” file and initialize your project with npm. Step 2: Now install two npm packages: “express” and “express-zip“. Step 3: Create an “index.

How do I download a file from node server?

Method 1: Using 'https' and 'fs' module We can use the http GET method to fetch the files that are to be downloaded. The createWriteStream() method from fs module creates a writable stream and receives the argument with the location of the file where it needs to be saved.

How do I download from Express?

Installing Express Use the following command to install express: npm install express --save.


1 Answers

If you already have the pdf as a readable stream, you can just do something like:

res.attachment('pdfname.pdf');
pdfstream.pipe(res);

Or if you have the pdf on disk, you can send it to the client simply with:

res.download('/path/to/file.pdf');

Or specify a custom filename that's presented to the browser:

res.download('/path/to/file.pdf', 'pdfname.pdf');
like image 188
mscdex Avatar answered Oct 20 '22 05:10

mscdex