1

I am trying to download some files using SFTP in Node. I know I have to handle the stream but I am not sure how I should do this and save the file in my local machine (in the downloads folder).

app.get('/download', (req, res) => {
    var Client = require('ssh2-sftp-client');
    var sftp = new Client();

    var config = {
        host: 'host123',
        port: '22',
        username: 'username',
        password: 'secretpassword'
    };

    sftp.connect(config).then((data) => {
        res.download(data);
    });
});

Thanks!

carlos E.
  • 115
  • 2
  • 11

1 Answers1

-1

reference Download a file from NodeJS Server using Express

sftp.connect allow you stream data. you can pipe it to response

app.get('/download', (req, res) => {
                var Client = require('ssh2-sftp-client');
                var sftp = new Client();

    var config = {
            host: 'host123',
            port: '22',
            username: 'username',
            password: 'secretpassword'
    };

    sftp.connect(config)
    .then(()=>{
        return sftp.get(remoteFilePath, [useCompression], [encoding]);
    })
    .then((data) => {
            fs.createWriteStream(data).pipe(res);
    });
});
shivshankar
  • 2,067
  • 1
  • 18
  • 28
  • I get a "(node:14796) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: path must be a string or Buffer". – carlos E. Dec 08 '17 at 14:43
  • I changed the `remoteFilePath` to the location of the file I am trying to get, but when I did, I got an error code `(node:7952) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: useCompression is not defined`. – carlos E. Dec 11 '17 at 16:30