diff --git a/lib/internal/fs/cp/cp.js b/lib/internal/fs/cp/cp.js index 0724eb730db..b632c650681 100644 --- a/lib/internal/fs/cp/cp.js +++ b/lib/internal/fs/cp/cp.js @@ -54,6 +54,7 @@ const { resolve, sep, } = require('path'); +const fsBinding = internalBinding('fs'); async function cpFn(src, dest, opts) { // Warn about using preserveTimestamps on 32-bit node @@ -344,7 +345,10 @@ async function onLink(destStat, src, dest, opts) { if (!isAbsolute(resolvedDest)) { resolvedDest = resolve(dirname(dest), resolvedDest); } - if (isSrcSubdir(resolvedSrc, resolvedDest)) { + + const srcIsDir = fsBinding.internalModuleStat(src) === 1; + + if (srcIsDir && isSrcSubdir(resolvedSrc, resolvedDest)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${resolvedSrc} to a subdirectory of self ` + `${resolvedDest}`, diff --git a/test/parallel/test-fs-cp.mjs b/test/parallel/test-fs-cp.mjs index dbdb0b7b19e..7a89d0d859b 100644 --- a/test/parallel/test-fs-cp.mjs +++ b/test/parallel/test-fs-cp.mjs @@ -248,7 +248,7 @@ function nextdir(dirname) { ); } -// It allows copying when is not a directory +// It allows cpSync copying symlinks in src to locations in dest with existing synlinks not pointing to a directory. { const src = nextdir(); const dest = nextdir(); @@ -259,6 +259,23 @@ function nextdir(dirname) { cpSync(src, dest, mustNotMutateObjectDeep({ recursive: true })); } +// It allows cp copying symlinks in src to locations in dest with existing synlinks not pointing to a directory. +{ + const src = nextdir(); + const dest = nextdir(); + mkdirSync(src, mustNotMutateObjectDeep({ recursive: true })); + writeFileSync(`${src}/test.txt`, 'test'); + symlinkSync(resolve(`${src}/test.txt`), join(src, 'link.txt')); + cp(src, dest, { recursive: true }, + mustCall((err) => { + assert.strictEqual(err, null); + + cp(src, dest, { recursive: true }, mustCall((err) => { + assert.strictEqual(err, null); + })); + })); +} + // It throws error if symlink in dest points to location in src. { const src = nextdir();