How to download multiple files with ssh2-sftp-client fastGet?

3.1k views Asked by At

How do you download multiple txt files with fastGet? My code is as follows:

const Client = require('ssh2-sftp-client');
const sftp = new Client();

sftp.connect(configs)
    .then(() => {
        return sftp.list('.');
    })
    .then(files => {
        files.forEach(file => {
            if(file.name.match(/txt$/)){
                const remoteFile = // remote file dir path
                const localFile = // local file dir path
                sftp.fastGet(remoteFile, localFile).catch(err => console.log(err));
            }
        });
    })
    .catch(err => console.log(err))
    .finally(() => {
        sftp.end();
    });

I keep getting a no sftp connection available error. I'm pretty sure I'm doing a few things wrong here with sftp.fastGet but don't know exactly what or where to start.

1

There are 1 answers

0
Dhruv Shah On BEST ANSWER

There seem to be multiple issues in your code:

  1. The loop through files should be executed in the first then block itself.
  2. sftp.fastGet returns a promise, hence its an asynchronous, operation, and executing asynchronous operations inside a forEach loop is not a good idea.

I would recommend updating your code with following changes:

sftp.connect(configs)
    .then(async () => {
        const files = await sftp.list('.');

        for(const file in files){
          if(file.name.match(/txt$/)){
            const remoteFile = // remote file dir path
            const localFile = // local file dir path
            try {
              await sftp.fastGet(remoteFile, localFile)
            }
            catch(err) { 
              console.log(err))
            };
          } 
        }
    })
    .catch(err => console.log(err))
    .finally(() => {
        sftp.end();
    });