微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 ssh2-sftp-client 中使用 npm cli-progress

如何解决如何在 ssh2-sftp-client 中使用 npm cli-progress

我有一个使用 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% 处停止

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。