Skip to content

Instantly share code, notes, and snippets.

@yannbf
Forked from luciopaiva/walksync.js
Created October 11, 2018 09:17
Show Gist options
  • Save yannbf/763476f43a8754d1f64714540432a3f6 to your computer and use it in GitHub Desktop.
Save yannbf/763476f43a8754d1f64714540432a3f6 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