Skip to content

Commit

Permalink
fs: use async directory processing in cp()
Browse files Browse the repository at this point in the history
The readdir() functions do not scale well, which is why
opendir(), etc. were introduced. This is exacerbated in the
current cp() implementation, which calls readdir() recursively.

This commit updates cp() to use the opendir() style iteration.

PR-URL: #41351
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Tierney Cyren <[email protected]>
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Juan José Arboleda <[email protected]>
Reviewed-By: Mohammed Keyvanzadeh <[email protected]>
  • Loading branch information
cjihrig authored and danielleadams committed Feb 1, 2022
1 parent 970de53 commit 66556b3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
24 changes: 16 additions & 8 deletions lib/internal/fs/cp/cp-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const {
existsSync,
lstatSync,
mkdirSync,
readdirSync,
opendirSync,
readlinkSync,
statSync,
symlinkSync,
Expand Down Expand Up @@ -275,14 +275,22 @@ function mkDirAndCopy(srcMode, src, dest, opts) {
}

function copyDir(src, dest, opts) {
readdirSync(src).forEach((item) => copyDirItem(item, src, dest, opts));
}
const dir = opendirSync(src);

try {
let dirent;

function copyDirItem(item, src, dest, opts) {
const srcItem = join(src, item);
const destItem = join(dest, item);
const { destStat } = checkPathsSync(srcItem, destItem, opts);
return startCopy(destStat, srcItem, destItem, opts);
while ((dirent = dir.readSync()) !== null) {
const { name } = dirent;
const srcItem = join(src, name);
const destItem = join(dest, name);
const { destStat } = checkPathsSync(srcItem, destItem, opts);

startCopy(destStat, srcItem, destItem, opts);
}
} finally {
dir.closeSync();
}
}

function onLink(destStat, src, dest) {
Expand Down
12 changes: 6 additions & 6 deletions lib/internal/fs/cp/cp.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const {
copyFile,
lstat,
mkdir,
readdir,
opendir,
readlink,
stat,
symlink,
Expand Down Expand Up @@ -325,11 +325,11 @@ async function mkDirAndCopy(srcMode, src, dest, opts) {
}

async function copyDir(src, dest, opts) {
const dir = await readdir(src);
for (let i = 0; i < dir.length; i++) {
const item = dir[i];
const srcItem = join(src, item);
const destItem = join(dest, item);
const dir = await opendir(src);

for await (const { name } of dir) {
const srcItem = join(src, name);
const destItem = join(dest, name);
const { destStat } = await checkPaths(srcItem, destItem, opts);
await startCopy(destStat, srcItem, destItem, opts);
}
Expand Down

0 comments on commit 66556b3

Please sign in to comment.