Last active
June 27, 2022 20:21
-
-
Save wiedymi/13e44c828c7ac062e71f7fb3b408822e to your computer and use it in GitHub Desktop.
Dump ftp folder (Node.js)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config() | |
const ftp = require('ftp') | |
const fs = require('fs') | |
const { promisify } = require('util') | |
const env = { | |
host: process.env.FTP_HOST, | |
user: process.env.FTP_USER, | |
password: process.env.FTP_PASS, | |
folder: process.env.FTP_FOLDER || '/' | |
} | |
if (!env.host) { | |
return console.log('No FTP_HOST provided') | |
} | |
if (!env.user) { | |
return console.log('No FTP_USER provided') | |
} | |
if (!env.password) { | |
return console.log('No FTP_PASS provided') | |
} | |
const client = new ftp() | |
client.asyncList = promisify(client.list) | |
client.asyncGet = promisify(client.get) | |
async function getElements(folder) { | |
const result = await client.asyncList(folder) | |
return result.map(({ name, type }) => ({ name, isFolder: type === 'd' })) | |
} | |
const downloadFile = async (file, path) => { | |
const backupFolder = `./backup/` | |
await fs.promises.mkdir(backupFolder, { recursive: true }); | |
return new Promise((res) => { | |
const ws = fs.createWriteStream(path); | |
file.pipe(ws); | |
file.on('end', () => { res(); console.log(`${path} downloaded`) }); | |
}) | |
} | |
const handleReady = async (folder = env.folder) => { | |
try { | |
const elements = await getElements(folder) | |
for (const { name, isFolder } of elements) { | |
if (isFolder) { | |
const backupFolder = `./backup/${folder + name}`.replace(env.folder, '') | |
await fs.promises.mkdir(backupFolder, { recursive: true }); | |
await handleReady(folder + name + "/") | |
} else { | |
const filePath = `./backup/${folder + name}`.replace(env.folder, '') | |
if (!fs.existsSync(filePath)) { | |
const file = await client.asyncGet(folder + name) | |
await downloadFile(file, filePath) | |
} else { | |
console.log(`${filePath} has been downloaded already`) | |
} | |
} | |
} | |
if (folder === env.folder) { | |
console.log('Backup is ready') | |
client.end() | |
} | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
try { | |
client.connect({ | |
host: env.host, | |
password: env.password, | |
user: env.user, | |
}) | |
client.on('ready', handleReady); | |
} catch (error) { | |
console.log('Something went wrong') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment