Skip to content

Instantly share code, notes, and snippets.

@bchumney
Last active January 23, 2025 01:46
Show Gist options
  • Select an option

  • Save bchumney/5a9775967d652a460438719c01891bd2 to your computer and use it in GitHub Desktop.

Select an option

Save bchumney/5a9775967d652a460438719c01891bd2 to your computer and use it in GitHub Desktop.
Walk directory for files in nodejs
const fs = require('fs'),
path = require('path'),
fs_promise = fs.promises;
async function walk(dir) {
let files = await fs_promise.readdir(dir);
files = await Promise.all(files.map(async file => {
let filePath = path.join(dir, file);
let stats = await fs_promise.stat(filePath);
if (stats.isDirectory()) {
return walk(filePath);
}
else if(stats.isFile()) {
return filePath;
}
}));
return files.reduce((all, folderContents) => all.concat(folderContents), []);
}
//example usage
walk(directory).then(function(files){
files.sort();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment