I am trying to download files and folders via SFTP to my local machine.I am using the below code and am able to download the files in a particular directory but am unable to download the folders(with their respective files and folders recursively) in the same directory
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('')
});
}
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');
});
来源:https://stackoverflow.com/questions/55297097/how-do-i-download-directory-with-all-files-and-folders-inside-using-npm-module-s