Skip to content

Instantly share code, notes, and snippets.

@SaintPeter
Created August 17, 2018 01:58
Show Gist options
  • Save SaintPeter/5f8a710f19a21ec666af92ae6ec24513 to your computer and use it in GitHub Desktop.
Save SaintPeter/5f8a710f19a21ec666af92ae6ec24513 to your computer and use it in GitHub Desktop.
Node.js Simple Depth First Directory Traverse
fs = require('fs');
// Initialize the stack with the path on the command line
let stack = [
{
path: process.argv[2],
level: 1
}
];
while(stack.length > 0) {
// Fetch the current active node
const current = stack.pop();
// Print the current directory
console.log(" ".repeat(current.level - 1) + "+ " + current.path);
// List the directory
const fileList = fs.readdirSync(current.path);
// Iterate through the directory elements
fileList.forEach(filename => {
const fullPath = current.path + '\\'+ filename;
// Check if it's a directory
if(fs.statSync(fullPath).isDirectory()) {
stack.push({
path: fullPath,
level: current.level + 1
});
} else {
console.log(" ".repeat(current.level) + "|- " + filename);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment