Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List all files in a directory in Node.js recursively in a synchronous fashion
#!/usr/bin/env node
const
path = require("path"),
fs = require("fs");
/**
* List all files in a directory recursively in a synchronous fashion
*
* @param {String} dir
* @returns {IterableIterator<String>}
*/
function *walkSync(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const pathToFile = path.join(dir, file);
const isDirectory = fs.statSync(pathToFile).isDirectory();
if (isDirectory) {
yield *walkSync(pathToFile);
} else {
yield pathToFile;
}
}
}
const absolutePath = path.resolve(__dirname, "/home/some-user/some-folder/");
for (const file of walkSync(absolutePath)) {
// do something with it
console.info(file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.