Skip to content

Commit 5c9b517

Browse files
committed
fs: fix errorOnExist behavior for directory copy in fs.cp
1 parent 746c3c2 commit 5c9b517

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

lib/internal/fs/cp/cp.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,17 @@ async function setDestTimestamps(src, dest) {
300300
return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime);
301301
}
302302

303-
function onDir(srcStat, destStat, src, dest, opts) {
303+
async function onDir(srcStat, destStat, src, dest, opts) {
304304
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+
}
305314
return copyDir(src, dest, opts);
306315
}
307316

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}));

0 commit comments

Comments
 (0)