简体   繁体   中英

how to use npm cli-progress in ssh2-sftp-client

i have a project with npm ssh2-sftp-client to download files from remote server,so i want to display downloading progress displaying in console.Downloading files works fine, but i do not know how to use cli-progress to display downloading progress while the files are downloading.

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);
   }
  }); 
   

I have revised, hopefully it will be better

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();
            }
        }
    }
}

i followed the suggestion from @Abbas Agus Basari like:

 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+'%】');
    }
 });  

and run like: [1]: https://i.stack.imgur.com/97sRi.png i downloaded two files from remote server,but the console only could see one file 100%,the other stopped at 59%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM