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 <luigipinca@gmail.com>
Reviewed-By: Tierney Cyren <hello@bnb.im>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com>
Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com>
  • Loading branch information
cjihrig authored and targos committed Jan 14, 2022
1 parent 1f6c4e8 commit d4a6f2c
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
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
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 d4a6f2c

Please sign in to comment.