Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created March 14, 2014 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benfoster/9543337 to your computer and use it in GitHub Desktop.
Save benfoster/9543337 to your computer and use it in GitHub Desktop.
Resolving backpressure manually in node.js
var http = require('http'),
fs = require('fs');
var server = http.createServer(function(request, response) {
var file = fs.createWriteStream('upload.jpg'),
fileBytes = request.headers['content-length'],
uploadedBytes = 0;
request.on('data', function(chunk) {
uploadedBytes += chunk.length;
var progress = (uploadedBytes / fileBytes) * 100;
response.write('progress: ' + parseInt(progress, 10) + '%\n');
var bufferOK = file.write(chunk);
if (!bufferOK) {
request.pause();
}
});
file.on('drain', function() {
request.resume();
});
request.on('end', function() {
response.end('upload complete\n');
});
});
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment