Home

Reading Directories

Similar to the reading of files and writing of files, reading directories have a few different syntaxes & approaches, including callbacks, promises, and even streams.

(This is part of a brief series on the fs module)

Use A Callback To Read A Directory

readdir:

const { readdir } = require('fs')
// NOTE: __dirname is the current directory
readdir(__dirname, (err, files) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(files);
});

Read Directories Synchronously

readdir:

const { readdirSync } = require('fs')
try {
  const files = readdirSync(__dirname)
  console.log(files);
} catch (err) {
  console.error(err);
}

Use A Promise To Read Directories

const { readdir } = require('fs/promises');
async function doWork() {
  const files = await readdir(__dirname);
  console.log(files);
}

doWork().catch((err) => {
  console.error(err);
});
Tags: