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

How to receive email in Node.js?
email, Node.js, JavaScript
Browse the PCORnet Common Data Model.
PCORnet, TypeScript
Explore the HL7 Reference Information Model.
HL7 RIM, TypeScript
Browse the SDTM model.
SDTM, TypeScript
Explore the content model behind SNOMED CT.
SNOMED CT, TypeScript
Visualizing the hierarchy of FHIR data types and resources.
FHIR, TypeScript
How to add npm dependencies from multiple package registries?
Validate JSON against TypeScript types and interfaces.
TypeScript, JSON
How to safely create directories using the native file system module in Node.js?
How to specify non-standard JSX/HTML attributes in TypeScript?
TypeScript, JSX
How to generate data URLs in JavaScript?
Browse the OMOP Common Data Model.
OMOP, TypeScript

Made by Anton Vasetenkov.

If you want to say hi, you can reach me on LinkedIn or via email. If you like my work, you can support me by buying me a coffee.