Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream files in node/express to client

I want to stream content to clients which is possibly stored in db, which they would save as files.

Obviously res.download would do the job nicely, but none of the response.* functions accept a stream, only file paths.

I had a look at res.download impl and it just sets Content-Disposition header and then a sendfile.

So I could achieve this using this post as a guide. Node.js: pipe stream to response freezes over HTTPS

But it seems I would miss out on all the wrapping aspects that res.send performs.

Am I missing something here or should I just do the pipe and not worry about it - what is best practice here?

Currently creating temp files so I can just use res.download for now.

like image 962
Tim Avatar asked Oct 28 '12 03:10

Tim


People also ask

How do I read a node JS stream file?

#!/usr/bin/env node const fs = require('fs'); Next, you will create a function below the switch statement called read() with a single parameter: the file path for the file you want to read. This function will create a readable stream from that file and listen for the data event on that stream.

Why node js is stream based?

Streams are one of the fundamental concepts of Node. js. Streams are a type of data-handling methods and are used to read or write input into output sequentially. Streams are used to handle reading/writing files or exchanging information in an efficient way.


2 Answers

Make sure that your AJAX request from the client has an appropriate 'responseType' set. for example like

$http({   method :'GET',   url : http://url,   params:{},   responseType: 'arraybuffer' }).success() 
like image 23
sasidhar79 Avatar answered Oct 02 '22 23:10

sasidhar79


You can stream directly to the response object (it is a Stream).

A basic file stream would look something like this.

function(req, res, next) {   if(req.url==="somethingorAnother") {     res.setHeader("content-type", "some/type");     fs.createReadStream("./toSomeFile").pipe(res);   } else {     next(); // not our concern, pass along to next middleware function   } } 

This will take care of binding to data and end events.

like image 136
Morgan ARR Allen Avatar answered Oct 02 '22 23:10

Morgan ARR Allen