5

2021 update: the ambiguity has been fixed in nodejs doc in an April 2021 commit


Edit: This is essentially an issue with node docs. See discussion here.


I'm trying the fs.Dir class which was added since node v12.12:

// hello-world.js
const fs = require('fs');

(async function () {
  const dir = await fs.promises.opendir(__dirname);
  for await (const dirent of dir) {
    console.log('name:', dirent.name, 'isDir:', dirent.isDirectory());
  }
  return dir.close();
})();

$ node hello-world.js

It seems to be working as expected, which logs out info of each file in the directory (not missing a single one), but in the end it throws (node:3218) UnhandledPromiseRejectionWarning: Error [ERR_DIR_CLOSED]: Directory handle was closed at Dir.close (internal/fs/dir.js:161:13). What am I doing wrong?

ZYinMD
  • 3,602
  • 1
  • 23
  • 32

1 Answers1

6

The async iterator for the dir object will close the dir automatically when the iteration finishes. This does not appear to be documented, but you can see that in the code here.

async* entries() {
    try {
      while (true) {
        const result = await this[kDirReadPromisified]();
        if (result === null) {
          break;
        }
        yield result;
      }
    } finally {
      await this[kDirClosePromisified]();
    }
  }
}

ObjectDefineProperty(Dir.prototype, SymbolAsyncIterator, {
  value: Dir.prototype.entries,
  enumerable: false,
  writable: true,
  configurable: true,
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Yes @jfriend00, thanks so much for digging into the source code for me! I think this magic behavior should be better documented, so I submitted an issue on their github. So far nobody responded (after 10 days). I'll come back and update when they do! – ZYinMD Sep 21 '20 at 14:51