From dae793863cebcdaae579fb6fbd553209e9a71861 Mon Sep 17 00:00:00 2001 From: Joshua Pohl Date: Sat, 5 Mar 2022 17:47:20 -0600 Subject: [PATCH] feat: write to temp files while downloading closes #37 --- bin/async.js | 12 ++++++++---- bin/util.js | 5 +++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/bin/async.js b/bin/async.js index 78e7ee7..7bdd0a0 100644 --- a/bin/async.js +++ b/bin/async.js @@ -16,6 +16,7 @@ import { getArchiveFilename, getFilename } from "./naming.js"; import { getEpisodeAudioUrlAndExt, getArchiveKey, + getTempPath, runFfmpeg, runExec, writeItemMeta, @@ -63,9 +64,10 @@ const download = async ({ }, }); + const tempOutputPath = getTempPath(outputPath); const removeFile = () => { - if (fs.existsSync(outputPath)) { - fs.unlinkSync(outputPath); + if (fs.existsSync(tempOutputPath)) { + fs.unlinkSync(tempOutputPath); } }; @@ -101,14 +103,14 @@ const download = async ({ await pipeline( got.stream(finalUrl).on("downloadProgress", onDownloadProgress), - fs.createWriteStream(outputPath) + fs.createWriteStream(tempOutputPath) ); } catch (error) { removeFile(); throw error; } - const fileSize = fs.statSync(outputPath).size; + const fileSize = fs.statSync(tempOutputPath).size; if (fileSize === 0) { removeFile(); @@ -121,6 +123,8 @@ const download = async ({ return; } + fs.renameSync(tempOutputPath, outputPath); + if (expectedSize && !isNaN(expectedSize) && expectedSize !== fileSize) { logMessage( "File size differs from expected content length. Suggestion: verify file works as expected", diff --git a/bin/util.js b/bin/util.js index ad0ce95..07a5c61 100644 --- a/bin/util.js +++ b/bin/util.js @@ -15,6 +15,10 @@ const parser = new rssParser({ defaultRSS: 2.0, }); +const getTempPath = (path) => { + return `${path}.tmp`; +}; + const getArchiveKey = ({ prefix, name }) => { return `${prefix}-${name}`; }; @@ -569,6 +573,7 @@ export { getFeed, getImageUrl, getItemsToDownload, + getTempPath, getUrlExt, getUrlEmbed, logFeedInfo,