Search code examples
node.jssftpssh2-sftp-client

Nodejs: Not able to download file from sftp server


I'm trying to download files from sftp in nodejs, I created sftp using springboot I'm able to connect and do get() and put() operation using python/Winscp/ssh commands.

I'm able to connect with my SFTP server but its not downloading the file, it just create empty file in my directory with 0 KB size. I'm not sure what's wrong. It is working if I don't run this in a loop or I have only one file.

I have tried almost all the answers on stack overflow but nothing works for me.

 let Client = require('ssh2-sftp-client');
let sftp = new Client();
const path = require('path')
require('events').EventEmitter.defaultMaxListeners = 1000;

function DownloadFromSFTP() {
    sftp.connect({
        host: '127.0.0.1',
        port: '2222',
        username: 'test',
        password: 'password',
        keepaliveInterval: 2000,
        keepaliveCountMax: 20
    }).then(() => {
        return sftp.list(path.resolve('C:\\Users\\akash\\Documents\\workspace-spring-tool-suite-4-4.8.1.RELEASE\\SFTPServer\\data'));
    }).then((data) => {
        let len = data.length;

        // THIS WILL WORK IF I REMOVE WHILE LOOP AND DO FOR ONE FILE.
        while (len--) {
            var remotePath = 'C:\\Users\\akash\\Documents\\workspace-spring-tool-suite-4-4.8.1.RELEASE\\SFTPServer\\data\\' + data[len].name;
            console.log(remotePath);
            var localPath = "./uploads/" + data[len].name;
            sftp.fastGet(remotePath, localPath, {
                concurrency: 640,
                Chunksize: 32768
            }, function (err) {
                if (err) throw err
                console.log("downloaded successfully")
            });
        }
    }).catch((err) => {
        console.log(err, 'catch error');
    }).finally(() => {
        sftp.end();
    });
}

DownloadFromSFTP();

Solution

  • Did not found the solution.

    The ugly solution was to downloaded the whole directory from SFTP instead of downloading file one by one.