问题描述
我有一个使用 npm ssh2-sftp-client 从远程服务器下载文件的项目,所以我想在控制台中显示下载进度。下载文件工作正常,但我不知道如何使用 cli-progress 来显示下载文件时的下载进度。
function getConnect(ip,name,pwd,remotepath,localpath) {
const sftp = new SftpClient();
sftp.connect({
host: ip,port: 22,username: name,password: pwd
}).then(async () => {
const files = await sftp.list(remotepath,'.');
for (var j = 0; j < files.length; j++) {
var e =files[j];
await sftp.fastGet(remotepath + "/" + e.name,localpath + "\\" + e.name);
}
});
解决方法
我已经修改了,希望会更好
function getConnect(ip,name,pwd,remotepath,localpath) {
const sftp = new SftpClient();
sftp.connect({
host: ip,port: 22,username: name,password: pwd
}).then(async () => {
const files = await sftp.list(remotepath,'.');
for (var j = 0; j < files.length; j++) {
var e =files[j];
//=================================================
const Throttle = require('throttle');
const progress = require('progress-stream');
const throttleStream = new Throttle(1); // create a "Throttle " instance that reads at 1 bps
const progressStream = progress({
length: e.size,time: 100,// ms
});
progressStream.on('progress',(progress) => {
process.stdout.write("\r" + " [" +e.name+"] downloaded ["+progress.percentage.toFixed(2)+"%]");
});
const outStream = createWriteStream(localpath);
throttleStream.pipe(progressStream).pipe(outStream);
try {
await sftp.get(remotepath + "/" + e.name,throttleStream,{ autoClose: false });
} catch {
console.log('sftp error',e);
} finally {
await sftp.end();
}
}
}
}
,
我遵循了@Abbas Agus Basari 的建议,例如:
await sftp.fastGet(secondPath + "/" + e.name,localPath + "\\" + e.name,{
step: step=> {
const percent = Math.floor((step / e.size) * 100);
process.stdout.write("\r" + "【"+e.name+"】downloaded【"+percent+'%】');
}
});
并像这样运行: [1]:https://i.stack.imgur.com/97sRi.png 我从远程服务器下载了两个文件,但控制台只能 100% 看到一个文件,另一个在 59% 处停止