Skip to content

Instantly share code, notes, and snippets.

@sixpetrov
Forked from luciopaiva/walksync.js
Created September 5, 2018 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sixpetrov/728b26e54c19e58b536a1e40a5247c0c to your computer and use it in GitHub Desktop.
Save sixpetrov/728b26e54c19e58b536a1e40a5247c0c 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