Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add solution #247

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
52 changes: 51 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
@@ -1 +1,51 @@
// write code here
'use strict';

const fs = require('fs/promises');
const path = require('path');

function isEqualParentPath(path1, path2) {
return (
path1
.split(path.sep)
.slice(0, path1.split(path.sep).length - 1)
.join(path.sep) ===
path2
.split(path.sep)
.slice(0, path2.split(path.sep).length - 1)
.join(path.sep)
);
}

async function moveFile(src, dest) {
try {
const absSrc = path.resolve(src);
const absDest = path.resolve(dest);

if (absSrc === absDest) {
return;
}

if (isEqualParentPath(absSrc, absDest)) {
await fs.rename(absSrc, absDest);

return;
}

const destStats = await fs.stat(absDest);

Choose a reason for hiding this comment

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

Before calling fs.stat on absDest, you should check if the destination path exists to avoid errors. Consider using fs.access to verify the existence of the path.

if (destStats.isDirectory()) {
await fs.rename(absSrc, `${absDest}/${absSrc.split(path.sep).pop()}`);

Comment on lines +36 to +37

Choose a reason for hiding this comment

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

When moving a file to a directory, ensure that the directory exists. If it doesn't, you might want to create it using fs.mkdir with the { recursive: true } option.

return;
}

await fs.moveFile(absSrc, absDest);
} catch (err) {

Choose a reason for hiding this comment

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

The fs.moveFile function does not exist in the fs/promises module. You should use fs.rename for moving files or consider using a third-party library like fs-extra that provides a move function.

// eslint-disable-next-line no-console
console.error(err.message);
}
}

const [, , source, destination] = process.argv;

moveFile(source, destination);
Loading