20

Sorry in advance, I have a couple of questions on createReadStream() here.

Basically what I'm doing is dynamically building a file and streaming it to the user using fs once it is finished. I'm using .pipe() to make sure I'm throttling correctly (stop reading if buffer's full, start again once it's not, etc.) Here's a sample of my code I have so far.

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've read in another StackOverflow question (sorry, lost it) that if you're using the regular res.send() and res.end() that .pipe() works great, as it calls the .send and .end and adds throttling.

That works fine for most cases, except I'm wanting to remove the file once the stream is complete and not using .pipe() means I'm going to have to handle throttling myself just to get a callback.

So I'm guessing that I'll want to create my own fake "res" object that has a .send() and .end() method that does what the res usually does, however on the .end() I'll put additional code to clean up the generated file. My question is basically how would I pull that off?

Help with this would be much appreciated, thanks!

AlbertEngelB
  • 16,016
  • 15
  • 66
  • 93
  • possible duplicate of [Download file from NodeJS Server](http://stackoverflow.com/questions/7288814/download-file-from-nodejs-server) – loganfsmyth Feb 19 '13 at 16:55
  • That does indeed answer my file download question, thanks! I'll update the question to reflect only the .pipe() question. – AlbertEngelB Feb 19 '13 at 17:49

1 Answers1

33

The first part about downloading can be answered by Download file from NodeJS Server.

As for removing the file after it has all been sent, you can just add your own event handler to remove the file once everything has been 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 isn't 100% needed, but then you don't delete the file if there was an error while you were trying to send it.

Community
  • 1
  • 1
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 1
    Ahh, brilliant! I didn't know you could add events when you pipe streams. I assumed that you could only have one event handler per event and it would have been consumed by the pipe() call. Thanks! – AlbertEngelB Feb 19 '13 at 18:53