Home › Resources & tools › Walking a directory in Node.js

Walking a directory in Node.js

To recursively walk through the directory tree and get the path of each file in the tree, use the following code snippet:

const fs = require("fs");
const path = require("path");

function walkDirectory(directoryPath: string) {
  return fs.readdirSync(directoryPath).flatMap((fileOrSubdirectory) => {
    const fileOrSubdirectoryPath = path.join(directoryPath, fileOrSubdirectory);
    if (fs.statSync(fileOrSubdirectoryPath).isDirectory()) {
      return walkDirectory(fileOrSubdirectoryPath);
    }
    return [fileOrSubdirectoryPath];
  })
};

const files = walkDirectory("/path/to/directory");

See also

Osage Alphabet Poster, English-Labeled
$17.99

The Osage alphabet chart.

In development
Electroglottograph

Measure vocal fold contact area and contact duration during speech production.

Primates Evolutionary Tree Poster
$15.99

A poster featuring the phylogenetic tree of primates.

Wave Poster, English-Labeled
$19.99

A poster featuring a wave plot.

Bloch Sphere Poster, English-Labeled
$19.99

A poster featuring the Bloch sphere.

Receiving email with Node.js

How to receive email in Node.js?

Safely creating new directories using the Node.js File System API

How to safely create directories using the native file system module in Node.js?

Loading npm dependencies from multiple registries

How to add npm dependencies from multiple package registries?

Generating data URLs in JavaScript

How to generate data URLs in JavaScript?

Declaring custom JSX/HTML attributes in TypeScript

How to specify non-standard JSX/HTML attributes in TypeScript?

All prices listed are in United States Dollars (USD). Visual representations of products are intended for illustrative purposes. Actual products may exhibit variations in color, texture, or other characteristics inherent to the manufacturing process.