theophilusx / ssh2-sftp-client

a client for SSH2 SFTP
Apache License 2.0
797 stars 195 forks source link

Dynamic name for local filepath? #519

Closed blaasvaer closed 5 months ago

blaasvaer commented 5 months ago

I can't seem to figure out from the docs HOW to simply 'get' a file and store it locally with the same name as the file itself (just in another local path)?

From the Docs:

let client = new Client();

let remotePath = '/remote/server/path/file.txt';
let dst = fs.createWriteStream('/local/file/path/copy.txt');

// I WANT dst TO BE DYNAMIC, AND NOT PREDEFINED
// BUT .get NEEDS THIS BEFOREHAND?

client.connect(config)
  .then(() => {
    return client.get(remotePath, dst);
  })
  .then(() => {
    client.end();
  })
  .catch(err => {
    console.error(err.message);
  });

Seem like I have to go through hoops and loops to simple copy a file from the remote server to the local machine.

I'm looking for something along these lines:

const sftp = new Client( 'whatever-sftp' );

    sftp.connect( config )
    .then(() => {
        return sftp.list('/remote-dir-path');
    })
    .then( files => {
        files.forEach( file => {
            let file_destination = fs.createWriteStream('./local-path/' + file.name);

            sftp.get( '/remote-dir-path/' + file.name, file_destination );
        });
    })
    .then(() => {
        return sftp.end();
    })
    .catch(err => {});
theophilusx commented 5 months ago

You have to specify the destination filename at some point, either as part of the call or as part of the creation of the write stream, no avoiding it. As you have to specify the remote file name, I don't see it is much extra work to also attach that name to the destination path. Certainly not what I would consider 'hoops and loops'.