node.js - 如何使用 Nodejs 的 npm 模块 ssh2 下载包含所有文件和文件夹的目录?

标签 node.js npm sftp ssh2

我正在尝试通过 SFTP 将文件和文件夹下载到本地计算机。我正在使用以下代码,并且能够下载特定目录中的文件,但无法下载同一目录中的文件夹(及其各自的文件和文件夹递归)

 const folderDir=moment().format('MMM YYYY/D');
 const remoteDir = '/var/www/html/view';
 const remoteDir = 'Backup';

const download=(remoteDir,folderDir,FolderName)=>{

conn.on('ready', function() {

    conn.sftp((err, sftp) => {
      if (err) throw err;
      sftp.readdir(remoteDir, (err, list) => {
        if (err) throw err;
        let count = list.length;
        list.forEach(item => {
          let remoteFile = remoteDir + '/' + item.filename;
          var localFile = 'C:/Users/Desktop/'+folderDir+'/'+FolderName+'/' + item.filename;
          //console.log('Downloading ' + remoteFile);
          sftp.fastGet(remoteFile, localFile, (err) => {
            if (err) throw err;
            //console.log('Downloaded to ' + localFile);
            count--;
            if (count <= 0) {
              conn.end();
            }
          });
        });
      });
    });



  }).connect({
    host: '0.0.0.0',
    port: 0,
    username: 'test',
    privateKey: require('fs').readFileSync('')
  });

}

最佳答案

通过运行安装模块:

npm i ssh2-sftp-client

你可以这样做:

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


sftp.connect({
    host: '',
    port: '22',
    username: 'your-username',
    password: 'your-password'
}).then(() => {
    // will return an array of objects with information about all files in the remote folder
    return sftp.list('/');
}).then(async (data) => {
    // data is the array of objects
    len = data.length;
    // x is one element of the array
    await data.forEach(x => {
        let remoteFilePath = '/' + x.name;
        sftp.get(remoteFilePath).then((stream) => {
            // save to local folder ftp
            let file = './ftp/' + x.name;
            fs.writeFile(file, stream, (err) => {
                if (err) console.log(err);
            });
        });
    });

}).catch((err) => {
    console.log(err, 'catch error');
});

For more info on the ssh2-sftp-client module.

关于node.js - 如何使用 Nodejs 的 npm 模块 ssh2 下载包含所有文件和文件夹的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55297097/

相关文章:

javascript - Node.js dom apis - jsdom、cheerio - 我可以使用 JS 命令还是需要使用 jQuery?

angular - 如何从 Angular 8 或 9 降级到 Angular 7

c# - SSH.NET SocketException尝试以其访问权限禁止的方式访问套接字

javascript - 如何映射 `.find()`返回的数据?

node.js - ESLint 同时输出到文件和控制台

node.js - 不能在控制指令或其他混入中定义函数

firebase - 如何在heroku上为Google Assistant部署Firebase功能

python - Paramiko/pysftp 连接失败并显示 "Negotiation failed/invalid DH value",但是 GUI 和 sftp 可以连接

windows - 使用 SFTP 将文件从 Windows 传输到 Linux

node.js - 转换错误 : Cast to ObjectId failed at path "_id"