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

"Hello, World!" Code Snippet Poster, JavaScript Programming Language
$14.99

A poster featuring the "Hello, World!" program in JavaScript programming language.

топология IPA Transcription Poster
$14.99

A poster featuring the phonetic transcription of "топология" in the International Phonetic Alphabet (IPA).

Menthol Molecule Poster, Ball-and-Stick Model, Stylized, English-Labeled
$19.99

A poster featuring the ball-and-stick model (stylized) of the menthol molecule.

صحراء Poster
$14.99

A poster featuring the word "صحراء".

Receiving email with Node.js

How to receive email in Node.js?

How to install Node.js and npm on a Mac using Homebrew

Homebrew is a package manager for macOS. This guide will help you install Node.js and npm using a Homebrew formula.

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?

TypeScript Validator

Validate JSON against TypeScript types and interfaces.

Loading npm dependencies from multiple registries

How to add npm dependencies from multiple package registries?

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. The products' design and underlying technology are protected by applicable intellectual property laws. Unauthorized reproduction or distribution is prohibited.