Some Node in my life

I’m a big time Rails fanboy, but I decided I needed some Node.js in my life. I wrote a little file uploader and the upload speed and the small number of lines written blew my mind.

//require libraries
var fs = require('fs');
var http = require('http');

http.createServer(function(request, response) {
  //create file we write data to
  var newFile = fs.createWriteStream("newfile.pdf");

  //get file size and initialize vars
  var fileBytes = request.headers['content-length'];
  var uploadedBytes = 0;
  var uploadStartTime = new Date();

  //while request is still readable respond back
  //with the upload percentage
  request.on('readable', function() {
    var chunk = null;
    while (null !== (chunk = request.read())) {
      uploadedBytes += chunk.length;
      var progress = (uploadedBytes / fileBytes) * 100;
      response.write("progress: " + parseInt(progress, 10) + "%\n");

    }
  });

  //transmitting file upload to dump file
  request.pipe(newFile);

  //send final message once file upload complete
  request.on('end', function() {
    var uploadStopTime = new Date();
    var timeElapsed = (uploadStopTime - uploadStartTime) / 1000;
    response.write('----------\n');
    response.write(timeElapsed + ' seconds elapsed' + '\n');
    response.end('File Uploaded!\n' + '----------');
  });
}).listen(3000);

Uploading a 12 MB file.

curl --upload-file ~/Downloads/twelve-mb-file.pdf http://localhost:3000
progress: 0%
progress: 1%
progress: 1%
progress: 2%
progress: 2%
progress: 3%
progress: 3%
progress: 4%
progress: 4%
...
...
progress: 96%
progress: 97%
progress: 97%
progress: 98%
progress: 98%
progress: 99%
progress: 99%
progress: 100%
----------
0.053 seconds elapsed
File Uploaded!
----------

It reminds me of when I went to college and started using a T1 internet connection instead of the 14.4k modem we were using at home. My roommate downloaded a 5 MB file online and we figured we would go to the dining hall and eat while the file downloaded. To our absolute shock and amazement the file downloaded in about 20 seconds. Our minds were completely blown.

Leave a Reply