Step 3

Let's update the server.js file:

const fs = require("fs");

const files = fs.readdirSync("./");

console.log(files);

Save the file and run it:

node server.js

You should see the following output:

[
  '.git',
  '.gitignore',
  '.nojekyll',
  'README.md',
  'index.html',
  'server.js'
]

The readdirSync will (synchronously) read the files stored in the given directory (the path to the directory is provided as an argument to readdirSync function). There is an asynchronous version of this function too:

fs.readdir("./", (err, files) => {
  console.log(err ? err : files);
});

Notice we have used the callback pattern to deal with the async operation. The readdir function was written before JavaScript had a Promise object. The function does not return a Promise, so we cannot use the Promise pattern (nor async/await) here.

If you want to use the async/await or promise syntax, you must write your own. However, some built-in modules have a promise-based alternative that has recently been added!

const fs = require("fs/promises");

async function _readdir(path) {
  try {
    const files = await fs.readdir(path);
    console.log(files);
  } catch (err) {
    console.log(err);
  }
}

_readdir("./");