Skip to content

Instantly share code, notes, and snippets.

@juliangruber
Created February 4, 2014 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliangruber/8800791 to your computer and use it in GitHub Desktop.
Save juliangruber/8800791 to your computer and use it in GitHub Desktop.
var http = require('http');
var Readable = require('stream').Readable;
http.createServer(function(req, res){
var stream = Readable();
stream._read = function(){
console.log('_read', Date.now());
if (stream.closed) return stream.push(null);
setTimeout(function(){
stream.push(Date.now()+'\n');
}, 100);
};
stream.close = function(){
console.log('close');
stream.closed = true;
};
req.on('close', function(){
stream.close();
});
stream.pipe(res);
}).listen(3000);
var http = require('http');
var Readable = require('stream').Readable;
http.createServer(function(req, res){
var stream = Readable();
stream._read = function(){
console.log('_read', Date.now());
setTimeout(function(){
stream.push(Date.now()+'\n');
}, 100);
};
stream.pipe(res);
}).listen(3000);

Readable stream cleanup issues.

Steps to reproduce:

  1. Run node leaks.js
  2. Issue a request to it, for example via curl http://localhost:3000
  3. Watch leaks.js repeatedly print _read <Date> to the console while the request is active
  4. Kill the request by killing curl
  5. leaks.js still keeps printing _read <Date>. The readable stream is still being read although the request ended

Fixed in fixed.js by implementing and calling a custom closing mechanism. The fact that we have to call the .close() manually means that if you just fs.createReadStream("/dev/random").pipe(res) you create a leak again.

Same in node 0.10 and 0.11.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment