Created
October 28, 2015 00:01
-
-
Save tatethurston/6240f5c6aea6ae6862bb to your computer and use it in GitHub Desktop.
node file upload progress streaming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var fs = require('fs'); | |
http.createServer(function(request, response){ | |
var newFile = fs.createWriteStream('file-upload.jpg'); | |
var fileSize = request.headers['content-length']; | |
var uploadedBytes = 0; | |
request.on('readable', function(){ | |
var chunk = request.read(); | |
while(chunk !== null){ | |
uploadedBytes += chunk.length; | |
chunk = request.read() | |
var progress = (uploadedBytes / fileSize) * 100; | |
response.write('Progress: ' + progress.toFixed(2) + '%\n'); | |
} | |
}); | |
request.pipe(newFile); | |
request.on('end', function(){ | |
response.end('File uploaded!'); | |
}); | |
}).listen(1337); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment