Skip to content

Instantly share code, notes, and snippets.

@luciopaiva
Forked from kethinov/walksync.js
Last active October 29, 2020 20:24
Show Gist options
  • Save luciopaiva/4ba78a124704007c702d0293e7ff58dd to your computer and use it in GitHub Desktop.
Save luciopaiva/4ba78a124704007c702d0293e7ff58dd to your computer and use it in GitHub Desktop.
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