Reputation: 7632
I am trying to send a (huge) file with a limited amount of data passing every second (using TooTallNate/node-throttle):
var fs = require('fs');
var Throttle = require('throttle');
var throttle = new Throttle(64);
throttle.on('data', function(data){
console.log('send', data.length);
res.write(data);
});
throttle.on('end', function() {
console.log('error',arguments);
res.end();
});
var stream = fs.createReadStream(filePath).pipe(throttle);
If I cancel the download at the clients browser, the stream will just continue until it completly transferred.
I also tested the scenario above with npm node-throttled-stream, same behavour.
How to cancel the stream if the browser closed his request?
I am able to obtain the connections close
event by using
req.connection.on('close',function(){});
But the stream
has neither a destroy
nor an end
or stop
property which I could use to stop the stream
from further reading.
I does provide the property pause
Doc, but I would rather stop node from reading the whole file than just stopping to recieve the contents (as described in the doc).
Upvotes: 2
Views: 1593
Reputation: 7632
I ended up using the following dirty workaround:
var aborted = false;
stream.on('data', function(chunk){
if(aborted) return res.end();
// stream contents
});
req.connection.on('close',function(){
aborted = true;
res.end();
});
As mentioned above, this isn't really a nice solution, but it works.
Any other solution would be highly appreciated!
Upvotes: 2