Skip to content

Instantly share code, notes, and snippets.

@pgkos
Last active August 29, 2015 14:21
Show Gist options
  • Save pgkos/f0a650daf56aa49899e9 to your computer and use it in GitHub Desktop.
Save pgkos/f0a650daf56aa49899e9 to your computer and use it in GitHub Desktop.
Node.js filesystem walker (prints the paths of all files in a directory)
fs = require('fs');
path = require('path');
function traverseDirectory(root) {
var visitedDirs = {}; // used as a set; all already visited folders
// (necessary because we visit symlinks)
var traverseRecursively = function(root) {
try {
var children = fs.readdirSync(root);
} catch (err) { return; }
for (var i = 0; i < children.length; i++) {
var childPath = path.join(root, children[i]);
try {
var fileStat = fs.statSync(childPath);
} catch (err) { return; }
if (fileStat.isDirectory()) {
try {
var childRealPath = fs.realpathSync(childPath);
} catch (err) { return; }
if (childRealPath in visitedDirs) {
continue;
} else {
visitedDirs[childRealPath] = true;
traverseRecursively(childPath);
}
} else if (fileStat.isFile()) {
console.log(childPath); // node hangs here
}
}
}
traverseRecursively(root);
}
traverseDirectory('/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment