mscdex / node-ftp

An FTP client module for node.js
MIT License
1.13k stars 243 forks source link

Getting Size of File Transferred #129

Closed helloanoop closed 9 years ago

helloanoop commented 9 years ago

Hello Everyone,

Is there any way of getting to know how much percentage of file has been transferred. We use node-ftp to deploy our build zip to the server.

Its ususally between 5 to 7 MB. We have to wait for a minute or two for the upload to get completed. It would be nice if we are able to display the percentage of the file upload.

Is this Possible?? Thanks in advance.

build

helloanoop commented 9 years ago

I found the answer at Issue#73.

After implementing the solution. This is my progress. build

helloanoop commented 9 years ago

But the long list of percentage displays were clumsy.

So I came up with a solution based on a StackOverflow answer to print the progress in a single line. Here is the entire script. Hope it might help someone,

var path = require('path');
var fs = require('fs');

var Client = require('ftp');

var c = new Client();

var connectionProperties = {
    host     : '*.*.*.*',
    user     : 'foo',
    password : 'bar'
};

var percentageComplete = 0;
var intervalId         = null;

function progressBar(){
  var i = 0;  // dots counter
  intervalId = setInterval(function() {
    process.stdout.clearLine();  // clear current text
    process.stdout.cursorTo(0);  // move cursor to beginning of line
    i = (i + 1) % 4;
    var dots = new Array(i + 1).join(".");
    process.stdout.write(percentageComplete  + ' % complete' + dots);  // write text
  }, 300);
}

c.on('ready', function () {
  console.log('Connected to FTP Server');

  var file  = fs.createReadStream('build.zip'),
      cur   = 0,
      total = fs.statSync('build.zip').size;

  file.on('data', function(d) {
    cur += d.length;
    percentageComplete = ((cur / total) * 100).toFixed(1);
  });

  progressBar();

  console.log('Transfer Begun...');
  c.put(file, 'build.zip', function(err) {
    clearInterval(intervalId);
    if (!err){
      console.log('\nTransfer Completed');
      console.log('Exiting Now');
      c.end();
    } else {
      throw err;
    }
  });
});

c.connect(connectionProperties);

This finished CLI look build