【问题标题】:How to download multiple files with ssh2-sftp-client fastGet?如何使用 ssh2-sftp-client fastGet 下载多个文件?
【发布时间】:2020-07-08 20:08:30
【问题描述】:

如何使用 fastGet 下载多个 txt 文件?我的代码如下:

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

我不断收到 no sftp connection available 错误。我很确定我在这里使用 sftp.fastGet 做错了一些事情,但不知道具体是什么或从哪里开始。

【问题讨论】:

    标签: node.js ssh2-sftp-client


    【解决方案1】:

    您的代码中似乎存在多个问题:

    1. loop through 文件应在第一个 then 块本身中执行。
    2. sftp.fastGet 返回一个承诺,因此它是一个 asynchronous 操作,并且在 forEach 循环内执行 asynchronous 操作不是一个好主意。

    我建议通过以下更改更新您的代码:

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

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多