0

I found plenty of walkers on npm but none is using an asynchronous iterator. Most of them are either using a callback or a promise leading to memory leaks on huge directories.

Is there any recent library using the following pattern:

async function* walk(dirPath) {
    // some magic…
    yield filePath;
}

To then use it like:

for await (const filePath of walk('/dir/path')) {
    console.log('file path', filePath);
}
1
  • Library recommendations are, as you should know by now, off topic here. Commented May 24, 2019 at 20:16

1 Answer 1

1

Okay, I simply made this walker using the synchronous readdir, it is very fast and memory efficient, I listed 2.5 millions of entries in around 3 minutes without any memory leak.

import path from 'path';
import fs, {Dirent} from 'fs';

function* walk(path:string):IterableIterator<string> {

    const entries:Dirent[] = fs.readdirSync(path, {withFileTypes: true});

    for (const entry of entries) {
        const entryPath:() => string = () => `${path}/${entry.name}`;

        if (entry.isFile()) {
            yield entryPath();
        }

        if (entry.isDirectory()) {
            yield* walk(entryPath());
        }
    }
}

Example of usage:

for (const path of walk(directoryPath)) {
    console.log(path);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.