From 85c44f497b09ea1ee43ce1b5f3c1112a768ed8f4 Mon Sep 17 00:00:00 2001 From: Denys Boiko Date: Sun, 31 May 2026 23:09:57 +0200 Subject: [PATCH] Solution --- src/app.js | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/app.js b/src/app.js index 0d15e7b..bca43b6 100644 --- a/src/app.js +++ b/src/app.js @@ -1 +1,51 @@ -// write code here +const fs = require('fs'); +const path = require('path'); + +function moveFile(src, dest) { + if (!src || !dest) { + throw new Error('Two arguments are required: '); + } + + if (!fs.existsSync(src)) { + throw new Error(`Source file not found: ${src}`); + } + + if (fs.statSync(src).isDirectory()) { + throw new Error(`Source is a directory, only files are supported: ${src}`); + } + + const destEndsWithSlash = dest.endsWith('/'); + + let finalDest; + + if (destEndsWithSlash) { + if (!fs.existsSync(dest) || !fs.statSync(dest).isDirectory()) { + throw new Error(`Destination directory does not exist: ${dest}`); + } + finalDest = path.join(dest, path.basename(src)); + } else if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) { + finalDest = path.join(dest, path.basename(src)); + } else { + const parentDir = path.dirname(dest); + + if ( + parentDir !== '.' && + (!fs.existsSync(parentDir) || !fs.statSync(parentDir).isDirectory()) + ) { + throw new Error(`Destination directory does not exist: ${parentDir}`); + } + finalDest = dest; + } + + fs.renameSync(src, finalDest); +} + +const [srcPath, destPath] = process.argv.slice(2); + +try { + moveFile(srcPath, destPath); +} catch (err) { + process.stderr.write(`Error: ${err.message}\n`); +} + +module.exports = { moveFile };