/*由AlexZ33创建*///fs模块varfs=require('fs');/**fs.open(path,flag,[mode],callback)*path:要打开的文件路径*flags:打开文件moderead/write*mode:设置文件读/写/执行的模式4/2/10777*callback:callback*err:文件打开失败的错误保存在err中,成功则err为null*fd:设置打开文件ID*/fs.open('1.txt','r',function(err,fd){console.log(err);console.log(fd);})fs.realpathSync//确保项目文件夹中的任何符号链接都已解析://https://github.com/facebookincubator/create-react-app/issues/637constappDirectory=fs.realpathSync(process.cwd());constresolveApp=relativePath=>路径.resolve(appDirectory,relativePath);https://github.com/1397467062...fs.readdirSyncfs.statSynchttps://github.com/JXtreehous...fs.readFileSyncfs.stat&fs.statSync1。异步版本:fs.stat(path,callback):path是表示路径的字符串,callback接收两个参数(err,stats),其中stats是fs.stats的一个实例;2、同步版本:fs.statSync(path)只接收一个path变量,fs.statSync(path)实际上是fs.stats的一个实例;3.查看fs.stats有以下几个方法:stats.isFile()stats.isDirectory()stats.isBlockDevice()stats.isCharacterDevice()stats.isSymbolicLink()(仅对fs.lstat()有效)stats.isFIFO()stats.isSocket()fs.accessSync常用utilsconstcreateFolder=function(folder){try{fs.accessSync(文件夹);}catch(e){fs.mkdirSync(文件夹);}};判别目录是否存在//ignorenotexistsdirconstexists=awaitfs.exists(logdir)if(!exists)return删除过期文件https://github.com/eggjs/egg-...//https://github.com/eggjs/egg-logrotator/blob/master/app/schedule/clean_log.js//删除过期日志文件:xxx.log.YYYY-MM-DDasyncfunctionremoveExpiredLogFile(logdir,maxDays,logger){//忽略不存在的目录constexists=awaitfs.exists(logdir)if(!exists)returnconstfiles=awaitfs.readdir(logdir)constexpiredDate=moment().subtract(maxDays,'days').startOf('日期');constnames=files.filter(file=>{constname=path.extname(file).substring(1)//扩展名去掉第一个点.if(!/^\d{4}\-\d{2}\-d{2}/.test(名称)){返回false}constdate=moment(name,'YYYY-MM-DD').startOf('date')if(!date.isValid()){returnfalse}returndate.isBefore(expiredDate)})if(names.lengh===0){返回;}console.log(`开始删除${logdir}文件:${names.join(',')}`)awaitPromise.all(names.map(name=>{constlogfile=path.join(logdir,name)returnfs.unlink(logfile).catch(err=>{err.message=`removelogfile${logfile}error,${err.message}`;thrownewError(err)})}))````##遍历目录中的文件目录引用:https://github.com/chenshenhai/koa2-note/blob/master/demo/mysql/util/walk-file.jsconstfs=require('fs')/**遍历目录下的文件目录@param{string}path解析要遍历的目录路径@param{string}mime遍历文件的后缀名@return{object}返回遍历的目录结果*/constgetFile=function(pathResolve,mime){letfiles=fs.readdirSync(pathResolve)letfileList={}for(let[i,item]offiles.entries()){letitemArr=item.split('\.')letitemMime=(我temAr.length>1)?itemArr[itemAr.length-1]:'undefined'letkeyName=item+''if(mime===itemMime){fileList[item]=pathResolve+item}}returnfileList}##windows下的路径问题//useageconstfs=require('fs')constgetFile=require('./fs.js')functiongetSqlMap(){letbasePath=__dirnamebasePath=basePath.replace(/\/g,'/')letpathArr=basePath.split('/')pathArr=pathArr.splice(0,pathArr.length-1)basePath=pathArr.join('/')+'/sql/'//D:/personal/data-manager/app/dao/sql/letfileList=getFile(basePath,'sql')returnfileList}console.log(getSqlMap())##递归读取取https://github.com/fs-utils/fs-readdir-recursivevarfs=require('fs')varpath=require('path')module.exports=readfunctionread(root,filter,文件,前缀){前缀=前缀||''文件=文件||[]过滤器=过滤器||noDotFilesvardir=path.join(root,prefix)//废了exitsif(!fs.existsSync(dir))return文件//if(fs.statSync(dir).isDirectory())fs.readdirSync(dir).filter(function(name,index){returnfilter(name,index,dir)}).forEach(function(name){read(root,filter,files,path.join(prefix,name))})elsefiles.push(prefix)returnfiles}functionnoDotFiles(x){returnx[0]!=='.'}##读取文件树并判断是否存在给输出的路径https://github.com/vuejs/vue-next/blob/master/scripts/utils.js`````constfs=require('fs')consttargets=(exports.targets=fs.readdirSync('packages').filter(f=>{if(!fs.statSync(`packages/${f}`).isDirectory()){returnfalse}constpkg=require(`../packages/${f}/package.json`)if(pkg.private&&!pkg.buildOptions){returnfalse}returntrue}))exports.fuzzyMatchTarget=(partialTargets,includeAllMatching)=>{constmatched=[]partialTargets.some(partialTarget=>{for(consttargetoftargets){if(target.match(partialTarget)){matched.push(target)if(!includeAllMatching){break}}}})if(matched.length){returnmatched}else{thrownewError(`Target${partialTargets}notfound!`)}}````#写操作````/*!*写
