node.js – Copy directory on ftp server using nodejs

Question:

I'm developing an application on nodejs where I need to access an ftp server and send some folders there. Before putting these folders, I want to back up the folders on the server. How can I copy a directory inside the ftp server? The idea is to change the folder 'servidor_ftp/folder1' to 'servidor_ftp/backup/folder1'

Do I need to download the folder first and then upload it to the server? I am currently using the ssh2-sftp-client module.

Answer:

I think the simplest solution would be to use the ssh2-sftp-client's own downloadDir() and uploadDir() methods to download the folder and send it to a new folder, which may be on another server.

Below is an example if the two folders are on the same server, if they are two folders on different servers you will have to make two connections with sftp.connect()

    const sftp = require('ssh-sftp-client');
    const config = {
       host: {
         host: host
         username: username
         password: password,
       }
       folder: folder          // pasta no servidor a ser baixada
       local: local            // pasta no projeto
       bkp: bkp                // pasta de backup
    }
    await sftp.connect(config.host);
    await sftp.downloadDir(config.folder, config.local);
    await sftp.uploadDir(config.local, config.bkp);
    await sftp.end();

You can also use libraries to compress the directory, like in this example

Using ssh2-sftp-client, I made a project similar to yours, but in my case I received a folder with .xls files from server A to transform into .csv and send to server B.

project link

Scroll to Top
AllEscort