Created
August 17, 2018 01:58
-
-
Save SaintPeter/5f8a710f19a21ec666af92ae6ec24513 to your computer and use it in GitHub Desktop.
Node.js Simple Depth First Directory Traverse
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
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