-
Notifications
You must be signed in to change notification settings - Fork 311
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
base: master
Are you sure you want to change the base?
add solution #247
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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); | ||
|
||
if (destStats.isDirectory()) { | ||
await fs.rename(absSrc, `${absDest}/${absSrc.split(path.sep).pop()}`); | ||
|
||
Comment on lines
+36
to
+37
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
return; | ||
} | ||
|
||
await fs.moveFile(absSrc, absDest); | ||
} catch (err) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
// eslint-disable-next-line no-console | ||
console.error(err.message); | ||
} | ||
} | ||
|
||
const [, , source, destination] = process.argv; | ||
|
||
moveFile(source, destination); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Before calling
fs.stat
onabsDest
, you should check if the destination path exists to avoid errors. Consider usingfs.access
to verify the existence of the path.