Skip to content
Open

task #342

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
60 changes: 60 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,61 @@
// write code here
/* eslint-disable no-console */
const fs = require('fs/promises');
const path = require('path');

async function isDirectoryExists(directoryPath) {
try {
const stats = await fs.stat(directoryPath);

return stats.isDirectory();
} catch (error) {
if (error.code === 'ENOENT') {
return false;
}
throw error;
}
}

async function moveFile() {
const [, , source, destination] = process.argv;

if (!source || !destination) {
console.error('Please provide both source and destination paths.');

return;
}

if (source === destination) {
return;
}

const lastChar = destination[destination.length - 1];
let newDestination = destination;

if (lastChar === '/') {
const directoryExists = await isDirectoryExists(destination);

if (!directoryExists) {
console.error('directory not exists');

return;
}

newDestination = destination + path.basename(source);
Comment on lines 35 to 44

Choose a reason for hiding this comment

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

This block has some issues with error handling. The await fs.stat(destination) call on line 36 will throw an error if the path doesn't exist. Additionally, the throw new Error(...) on line 39 is not caught anywhere. Both of these scenarios will cause an unhandled promise rejection and crash the application. This logic should be wrapped in a try...catch block to handle potential errors gracefully and provide a clear error message to the user, similar to how you handle the error for the fs.rename call.

} else {
const directoryExists = await isDirectoryExists(destination);

if (directoryExists) {
newDestination = destination + '/' + path.basename(source);
}
}

try {
await fs.rename(source, newDestination);
console.log(`Moved '${source}' to '${newDestination}'`);
} catch (error) {
console.error(`Error moving file: ${error.message}`);
}
}

moveFile();