GeezerVison is showing github.com — fs: fix errorOnExist behavior for directory copy in fs.cp · nodejs/node@434fcd7
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: lib/internal/fs/cp/cp.js +10-1Lines changed: 10 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -300,8 +300,17 @@ async function setDestTimestamps(src, dest) { | 300 | 300 | return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime); | 301 | 301 | } | 302 | 302 |
| 303 | | -function onDir(srcStat, destStat, src, dest, opts) { | | 303 | +async function onDir(srcStat, destStat, src, dest, opts) { | 304 | 304 | if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts); | | 305 | + if (opts.errorOnExist && !opts.force) { | | 306 | + throw new ERR_FS_CP_EEXIST({ | | 307 | + message: `${dest} already exists`, | | 308 | + path: dest, | | 309 | + syscall: 'cp', | | 310 | + errno: EEXIST, | | 311 | + code: 'EEXIST', | | 312 | + }); | | 313 | + } | 305 | 314 | return copyDir(src, dest, opts); | 306 | 315 | } | 307 | 316 |
| |
Collapse file Copy file name to clipboard +30Lines changed: 30 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +// This tests that cp() returns error if errorOnExist is true, force is false, | | 2 | +// and the destination directory already exists (even if contents don't conflict). | | 3 | + | | 4 | +import { mustCall } from '../common/index.mjs'; | | 5 | +import { nextdir } from '../common/fs.js'; | | 6 | +import assert from 'node:assert'; | | 7 | +import { cp, mkdirSync, writeFileSync } from 'node:fs'; | | 8 | +import tmpdir from '../common/tmpdir.js'; | | 9 | + | | 10 | +tmpdir.refresh(); | | 11 | + | | 12 | +const src = nextdir(); | | 13 | +const dest = nextdir(); | | 14 | + | | 15 | +// Create source directory with a file | | 16 | +mkdirSync(src); | | 17 | +writeFileSync(`${src}/file.txt`, 'test'); | | 18 | + | | 19 | +// Create destination directory with different file | | 20 | +mkdirSync(dest); | | 21 | +writeFileSync(`${dest}/other.txt`, 'existing'); | | 22 | + | | 23 | +// Should fail because dest directory already exists | | 24 | +cp(src, dest, { | | 25 | + recursive: true, | | 26 | + errorOnExist: true, | | 27 | + force: false, | | 28 | +}, mustCall((err) => { | | 29 | + assert.strictEqual(err.code, 'ERR_FS_CP_EEXIST'); | | 30 | +})); |
|