DEV Community

Dana Woodman
Dana Woodman

Posted on

7 1

Efficiently read files in a directory with Node.js opendir

Originally published on my blog.


Recently I had to scan the contents of a very large directory in order to do some operations on each file.

I wanted this operation to be as fast as possible, so I knew that if I used the standard fsPromises.readdir or fs.readdirSync which read every file in the directory in one pass, I would have to wait till the entire directoy was read before operating on each file.

Instead, I wanted to instead operate on the file the moment it was found.

To solve this, I reached for opendir (added v12.12.0) which will iterate over each found file, as it is found:

import { opendirSync } from "fs";

const dir = opendirSync("./files");
for await (const entry of dir) {
    console.log("Found file:", entry.name);
}
Enter fullscreen mode Exit fullscreen mode

fsPromises.opendir/openddirSync return an instance of Dir which is an iterable which returns a Dirent (directory entry) for every file in the directory.

This is more efficient because it returns each file as it is found, rather than having to wait till all files are collected.

Just a quick Node.js tip for ya 🪄


Follow me on Dev.to, Twitter and Github for more web dev and startup related content

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
emiroberti profile image
Emiliano Roberti

great i have a similar situation. I will do the same

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay