Skip to content
This repository was archived by the owner on Feb 5, 2022. It is now read-only.

Download progress #93

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
34 changes: 22 additions & 12 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});
});
};
Expand Down