0

我有一个带有 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);
   }
  }); 
   
4

2 回答 2

1

我已经修改了,希望会更好

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();
            }
        }
    }
}
于 2021-04-01T13:02:16.520 回答
0

我遵循了@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" + "【&quot;+e.name+"】downloaded【&quot;+percent+'%】');
    }
 });  

并运行如下:[1]:https ://i.stack.imgur.com/97sRi.png 我从远程服务器下载了两个文件,但控制台只能看到一个文件 100%,另一个停止在 59%

于 2021-04-02T00:28:19.223 回答