Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,41 @@
// write code here
const fs = require('fs');
const path = require('path');

function moveFiles() {
const [source, destination] = process.argv.slice(2);

try {
if (!source || !destination) {
throw new Error('Invzlid arguments');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a small typo here. It should be Invalid arguments.

}

if (!fs.existsSync(source) || !fs.statSync(source).isFile()) {
throw new Error('Source is not a file');
}

let finalDest = destination;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The requirements state that the app must support only moving files. The current implementation would also move a directory if it were provided as the source. It's a good practice to add a check here to verify that the source path is indeed a file before proceeding. You can use fs.statSync() for this, but remember to also handle cases where the source doesn't exist.


if (destination.endsWith('/')) {
if (
!fs.existsSync(destination) ||
!fs.statSync(destination).isDirectory()
) {
throw new Error('Destination directory does not exist');
}

finalDest = path.join(destination, path.basename(source));
} else if (
fs.existsSync(destination) &&
fs.statSync(destination).isDirectory()
) {
finalDest = path.join(destination, path.basename(source));
}
Comment on lines +18 to +32

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great job handling both cases for the destination directory (with and without a trailing slash). To make the code even cleaner, you could refactor this if/else if structure to avoid repeating the finalDest = path.join(...) line. You could use a variable to track if the destination is a directory, and then set finalDest once based on that variable.


fs.renameSync(source, finalDest);
} catch (error) {
// eslint-disable-next-line no-console
console.error(error.message);
}
}

moveFiles();
Loading