CreateReadStream (). pipe () callback

Sorry, I have some questions about createReadStream () here.

Basically what I am doing is dynamically creating the file and streaming it to the user using fs after its completion. I use .pipe () to make sure that I throttle correctly (stop reading if the buffer is full, start again if not, etc.) Here is an example of my code that I still have.

http.createServer(function(req, res) { var stream = fs.createReadStream('<filepath>/example.pdf', {bufferSize: 64 * 1024}) stream.pipe(res); }).listen(3002, function() { console.log('Server listening on port 3002') }) 

I read in another StackOverflow question (sorry, lost it) that if you use the usual res.send () and res.end (), that .pipe () works fine, as it calls .send and .end and adds throttling .

This works fine for most cases, except that I want to delete the file after the stream finishes and not use .pipe () means that I will have to handle throttling just to get a callback.

So, I assume that I would like to create my own fake res object, which has the .send () and .end () methods, which does what res normally does, but on .end () I will put extra code to clear the created file. My question is basically, how can I take this off?

Help with this would be very grateful, thanks!

+12
source share
1 answer

The first part on downloading can be answered Download a file from a NodeJS server .

As for deleting a file after it is sent, you can simply add your own event handler to delete the file as soon as everything is sent.

 var stream = fs.createReadStream('<filepath>/example.pdf', {bufferSize: 64 * 1024}) stream.pipe(res); var had_error = false; stream.on('error', function(err){ had_error = true; }); stream.on('close', function(){ if (!had_error) fs.unlink('<filepath>/example.pdf'); }); 

The error handler is not 100% needed, but then you do not delete the file if there was an error when you tried to send it.

+25
source

All Articles