Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fs: use async directory processing in cp()
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.
  • Loading branch information
cjihrig committed Dec 29, 2021
commit b5aa0b3b39e387fde919fa0a28148d34130b24c5
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
13 changes: 7 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,12 @@ 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 dirent of dir) {
const { name } = dirent;
Comment thread
cjihrig marked this conversation as resolved.
Outdated
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