-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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