diff --git a/README.md b/README.md index 319c0d4..6996fdb 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,42 @@ The high level client is an instance of `Client`, but it contains the high level download a server file to local. +### Example with progress bar (download from server) + +You can easily combine this module with the `progress` npm package, to get live progress data in your commandline interface. Example below: + +```javascript +var scp2 = require('scp2'); +var ProgressBar = require('progress'); + +var client = new scp2.Client(); +var bar; + +client.on('transfer', function(buf, downloaded, total) { + if (!bar) { + bar = new ProgressBar(' downloading [:bar] :rate/bps :percent :etas', { + complete: '=', + incomplete: ' ', + width: 20, + total: total + }); + } + bar.tick(buf.length); +}); + +scp2.scp({ + host: ..., + username: ..., + password: ..., + path: '/path/to/src/file' +}, '/path/to/dest/file', client, function(err) { + if (err) { + console.log(err); + } + + // Do stuff with the downloaded file +}); +``` ## Events diff --git a/lib/client.js b/lib/client.js index 4af629d..47a2966 100644 --- a/lib/client.js +++ b/lib/client.js @@ -292,18 +292,28 @@ Client.prototype.download = function(src, dest, callback) { return callback(err); } - var sftp_readStream = sftp.createReadStream(src); - sftp_readStream.on('error', function(err){ - callback(err); - }); - sftp_readStream.pipe(fs.createWriteStream(dest)) - .on('close',function(){ - self.emit('read', src); - self.close(); - callback(null); - }) - .on('error', function(err){ - callback(err); + sftp.open(src, 'r', function(err, fd) { + sftp.fstat(fd, function(err, stats) { + var bufferSize = stats.size; + var bytesDownloaded = 0; + + var sftp_readStream = sftp.createReadStream(src); + sftp_readStream.on('data', function(data) { + bytesDownloaded += data.length; + self.emit('transfer', data, bytesDownloaded, bufferSize); + }) + sftp_readStream.on('error', function(err){ + callback(err); + }); + sftp_readStream.pipe(fs.createWriteStream(dest)) + .on('close',function(){ + self.emit('read', src); + callback(null); + }) + .on('error', function(err){ + callback(err); + }); + }); }); }); };