Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local internet = require("internet")
- local fs = require("filesystem")
- local downloader = {}
- function downloader.downloadFile(url, savePath)
- local response = downloader._tryDownloadFile(url)
- downloader._saveDowloadFile(response, savePath)
- end
- function downloader._tryDownloadFile(url)
- local result, response = pcall(internet.request, url)
- if result == true then
- return response
- else
- error("Failed download file!")
- end
- end
- function downloader._saveDowloadFile(response, savePath)
- local file = downloader._prepareFileToWrite(savePath)
- for chunk in response do
- string.gsub(chunk, "\r\n", "\n")
- file:write(chunk)
- end
- file:close()
- end
- function downloader._prepareFileToWrite(path)
- downloader._deleteFileIfItExist(path)
- downloader._createFoldersIfItIsNessesary(path)
- local file, errorInfo = io.open(path, "w")
- downloader._throwErrorIfOpeningFileForWritingIsFailed(file, errorInfo)
- return file
- end
- function downloader._deleteFileIfItExist(path)
- if fs.exists(path) then
- fs.remove(path)
- end
- end
- function downloader._createFoldersIfItIsNessesary(path)
- local pathWithoutName = string.gsub(path, fs.name(path), " ")
- fs.makeDirectory(pathWithoutName)
- end
- function downloader._throwErrorIfOpeningFileForWritingIsFailed(file, errorInfo)
- if not file then
- error("Failed opening file for writing! " .. errorInfo)
- end
- end
- downloader.downloadFile("https://raw.githubusercontent.com/AmonDeShir/AmonLuaApi/master/console/menu.lua", "/home/edit/test.lua")
Add Comment
Please, Sign In to add comment