node.jssftpssh2-sftp

SFTP in Node.js uploading empty files


I'm having an issue with a project I'm working on whereby I'm downloading files from my FTP server using a node module called sftp-ssh2-client and then trying to pass the stream back into my FTP server but into a different directory.

The code looks like this:

const stream = sftp.get(`path/to/file.csv.gz`).then(() => {

}).catch((err) => {

});

sftp.put(stream, 'path/to/new/file.csv.gz').then(() => {

}).catch((err) => {

})

However, when I dial into my FTP server to the location where the file has been PUT to, the file size is 0 and when downloaded is corrupted. Can anyone tell me what I'm doing wrong here?

Many thanks,

G


Solution

  • sftp.get() doesn't return a stream, it returns a promise that resolves to a stream, so your code should look something like this:

    sftp.get('path/to/file.csv.gz').then(stream => {
      return sftp.put(stream, 'path/to/new/file.csv.gz');
    }).catch(err => {
      ...
    });
    

    However, it seems to me that you could just use sftp.rename(), which wouldn't require downloading and uploading the entire file:

    sftp.rename('path/to/file.csv.gz', 'path/to/new/file.csv.gz').then(...);
    

    Also, if you do want to take the download-then-upload route, make sure you read the documentation regarding encoding.