ivan-loh / mac-lookup

mac address manufacturer lookup for [node](http://nodejs.org).
14 stars 9 forks source link

User Experience enhancement for download of oui update file #6

Open gazdawg opened 8 years ago

gazdawg commented 8 years ago

When performing a rebuild the download of the latest oui.txt file (via my link) takes forever and I hate sitting there wondering if the process is running or stalled.

I've made a few alterations to my version of the this code which may be of benefit to anyone else using this great package.

The original code in index.js at 114

  request(this.options.url)
    .on('error', console.error)
    .on('end', function() {
      parse(next);
    })
    .pipe(fs.createWriteStream(this.options.txt));

The new code

  var bytesRead=0;
  var bytesToReceive=0;  
  request(this.options.url) 
    .on('response', function(response) {        
        if (response.statusCode != 200) {
            console.error("Request failed with status/code of :", response.statusCode);
            console.error('The accompanying message is:', response.statusMessage);
            throw new Error("Downloading of the Update has failed.");
        }
        else {
            bytesToReceive = Number(response.headers["content-length"]);
            console.log("Size of update is " + bytesToReceive.toLocaleString() + " bytes.");
        }
    })
    .on('data', function(data) {
        bytesRead += data.length;
        // stdout.write and using the \r allows us to rewrite on the same console line
        process.stdout.write("Received " + ((bytesRead/bytesToReceive) * 100).toFixed(2) + "% of the file...\r");
    })
    .on('end', function () {
        // prefix with a \n to leave the last "Received" message on the console
        console.log("\nDownload completed.");
    })  
    .on('error', console.error)
    .on('end', function() {
      parse(next);
    })
    .pipe(fs.createWriteStream(this.options.txt));

The difference to the overall output is an extra 3 lines, for example:

Size of update is 3,343,033 bytes. Received 100.00% of the file... Download completed.

The advantages of this refactor are:

Thanks for your consideration.

ivan-loh commented 8 years ago

cool, thanks. will get around to this on the weekend