Created
August 27, 2022 03:09
-
-
Save mLuby/712c11a0336aefad0f5e38cf7f2eb030 to your computer and use it in GitHub Desktop.
Example FTP script that connects to an FTP server, lists the directory's files, chooses one to download, renames it locally, then re-uploads it.
This file contains 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
import fs from "fs"; | |
import { fileURLToPath } from "url"; | |
import {join, parse, dirname} from "path"; | |
import FtpClient from "ftp"; | |
const FTP_READY_EVENT = "ready"; | |
const FS_CLOSE_EVENT = "close"; | |
const config = { // See https://www.npmjs.com/package/ftp#methods. | |
host: "ftp.dlptest.com", | |
user: "dlpuser", // Courtesy of https://dlptest.com/ftp-test/ | |
password: "rNrKYTX9g7z3RgJRmxWuGHbeu", | |
path: "", | |
} | |
const localDownloadsDir = join(dirname(fileURLToPath(import.meta.url)), "UNSAFE_DOWNLOADS/"); // https://stackoverflow.com/a/62892482/1862046 | |
const ftpClient = new FtpClient(); | |
ftpClient.on(FTP_READY_EVENT, () => { | |
ftpClient.list(config.path, (listErr, fileInfos) => { | |
if (listErr) throw listErr; | |
console.dir(fileInfos); | |
console.log("Found", fileInfos.length, "files"); | |
const fileInfo = fileInfos.find(({name, rights, size}) => size > 0 && /\.(json)$/i.test(name) && rights.other.includes('r')); | |
if (!fileInfo) { console.warn("No file found;"); ftpClient.end(); return; } | |
console.log("Found suitable file:", fileInfo.name, {size: fileInfo.size, ...fileInfo.rights}); | |
ftpClient.get(fileInfo.name, function(fileErr, fileStream) { | |
if (fileErr) throw fileErr; | |
console.log("Downloading", fileInfo.name, "to", localDownloadsDir); | |
const iteration = fileInfos.reduce((max, {name}) => Math.max(max, (name.match(/_v(\d+)\.[a-z]+$/) || [])[1] || 0), 0) + 1 | |
const localFilepath = join(localDownloadsDir, `${parse(fileInfo.name).name}_v${iteration}${parse(fileInfo.name).ext}`); | |
fileStream.pipe(fs.createWriteStream(localFilepath)); | |
fileStream.once(FS_CLOSE_EVENT, () => { | |
console.log("Download finished."); | |
const remoteFilename = `${parse(fileInfo.name).name}_v${iteration+1}${parse(fileInfo.name).ext}`; | |
console.log("Uploading", remoteFilename); | |
ftpClient.put(localFilepath, remoteFilename, (uploadErr) => { | |
if (uploadErr) throw uploadErr; | |
console.log("Upload finished; disconnecting."); | |
ftpClient.end(); | |
}); | |
}); | |
}); | |
}); | |
}); | |
ftpClient.connect(config); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment