How do I download directory with all files and folders inside using npm module ssh2 for nodejs?

三世轮回 提交于 2019-12-07 23:36:29

Install the module by running:

npm i ssh2-sftp-client

You can do it like this:

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!