Depth traversal and breadth traversal
There are two access sequences for nodes, depth-first traversal and breadth-limited traversal. The specific traversal sequence is shown as follows:
Breadth traversal deletes file directories
To make the implementation of each step clear, I graphed the directory structure of the files and indicated the order:
let fs = require('fs');
let path = require('path');
function preWide(dir){
let disArr=[dir] //[ 'a'] next(0) next(0)function next(index){
console.log(index,disArr)
fs.stat(disArr[index],(err,stats)=>{
if(stats.isdirectory ()){fs.readdir(disArr[index],(err,dirs)=>{ // index=0,dirs= ['a.js'.'b'.'d' ]
dirs=dirs.map(item=>path.join(disArr[index],item)) disArr=[...disArr,...dirs]'a'.'a\\a.js'.'a\\b'.'a\\d'Next (), index+1, and so on... next(index+1) }) }elseNext () next(index+1)}})}} preWide("a")
Copy the code
So, with the next() method, using index+1, we’ll keep going down the directory… Go down… All of a sudden, what if we find the head? Error reported… We need to stop it from going down when it finds its head, and at what point do we know it’s over?
To begin, we add if(index == disarr.length) return
function next(index){
console.log(index,disArr)
if(index == disArr.length) returnFs. stat(disArr[index],(err,stats)=>{...... })}Copy the code
Write a delete method, or according to the index, delete from the array.
function rmDir(index){
if(index < 0) returnFs. stat(disArr[index],(err,stats)=>{// Obtain the directory information by pathif(stats.isdirectory ()){// Yes folder fs.rmdir(disArr[index],(err)=>{// Delete folder asynchronouslyif(err){
throw err;
}else{
rmDir(index-1)
}
})
}else{// Yes file fs.unlink(disArr[index],(err)=>{// Delete the file asynchronouslyif(err){
throw err;
}
rmDir(index-1)
})
}
})
}
Copy the code
This is the end, if you have better ideas and ideas, welcome to share!
If you think it’s ok, please give it a thumbs-up. Thank you!