企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 异步先序广度删除文件夹 ``` function rmdirp(dir,cb){ let dirs = [dir] ,index = 0; function rmdir(){ let current = dirs[--index]; if(current){ fs.stat(current,(err,stat)=>{ if(stat.isDirectory()){ fs.rmdir(current,rmdir); }else{ fs.unlink(current,rmdir); } }); } } !function next(){ if(index===dir.length)return rmdir(); //说明index停止增长,所有文件已遍历完毕 let current = dirs[index++]; fs.stat(current,function(err,stat){ if(err)return cb(err); if(stat.isDirectory()){ fs.readdir(current,function(err,files){ dirs = [...dirs,...files.map(item=>path.join(current,item))]; }); }else{ next(); } }); }(); } ``` ## 异步先序深度删除文件夹 ``` function rmdir(dir,cb){ fs.readdir(dir,function(err,files){ // 读取到文件 function next(index){ if(index===files.length)return fs.rmdir(dir,cb); //=== 表示能遍历的都遍历完了,删除该层目录 let newPath = path.join(dir,files[index]); fs.stat(newPath,function(err,stats){ if(stats.isDirectory()){ // 如果是文件夹 // 要读的是b里的第一个 而不是去读c // 如果b里的内容没有了 应该去遍历c rmdir(newPath,()=>next(index++)); }else{ //删除文件后继续遍历即可 fs.unlink(newPath,next(index++)); } }); } next(0); }); } ``` ## 递归创建文件夹 ``` function mkdirP(dir,cb){ let paths = dir.split('/'); // [a,b,c,d] //a a/b a/b/c function next(index){ if(index>paths.length){ return cb&&cb(); } let newPath = paths.slice(0,index).join('/'); fs.access(newPath,function(err){ if(err){ // 如果文件不存在就创建这个文件 fs.mkdir(newPath,function(err){ next(index++); }) }else{ next(index++); //说明已有文件夹,跳过继续创建下一个文件夹 } }); } next(1) } ``` ## fs.constants ``` // fs.constants.F_OK - path is visible to the calling process. This is useful for determining if a file exists, but says nothing about rwx permissions. Default if no mode is specified. // fs.constants.R_OK - path can be read by the calling process. // fs.constants.W_OK - path can be written by the calling process. // fs.constants.X_OK - path can be executed by the calling process. This has no effect on Windows (will behave like fs.constants.F_OK). ``` ## atime、mtime、ctime、birthtime ![](https://box.kancloud.cn/80128f5ecf680f880eeb28283cea9258_1017x315.png) ## watchFile // fs.watchFile() // current 是当前状态 prev是上一次的状态 let fs = require('fs'); let path = require('path'); fs.watchFile(path.join(__dirname,'2.txt'),{ persistent:true ,interval:4000 },function(cur,prev){ console.log('cur.ctime:',cur.ctime); console.log('prev.ctime:',prev.ctime); if(Date.parse(cur.ctime)===0){ //当前文件时间没有了 console.log('删除'); }else if(Date.parse(prev.ctime)===0){ // 上一次没有 现在有了 console.log('创建') }else{ console.log('修改') } }) // 文件不存在或则文件删除时的cur.ctime都为0 // cur.ctime: 1970-01-01T00:00:00.000Z // prev.ctime: 1970-01-01T00:00:00.000Z // 删除 // cur.ctime: 2018-03-20T14:57:48.236Z // prev.ctime: 1970-01-01T00:00:00.000Z // 创建 // 删除时 // cur.ctime: 1970-01-01T00:00:00.000Z // prev.ctime: 2018-03-20T14:57:48.236Z // 删除 //但文件删除后又创建的cur.ctime为上一次删除时的时间 // cur.ctime: 2018-03-20T14:58:06.894Z // prev.ctime: 2018-03-20T14:57:48.236Z // 修改 ## 创建文件 node中没有直接创建文件的命令 但我们可以通过`fs.writeFile`