当前位置: 首页 > 后端技术 > Node.js

节点学习记录:fs模块

时间:2023-04-03 10:51:52 Node.js

/*由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下的路径问题![clipboard.png](/img/bVbxQri)//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())![clipboard.png](/img/bVbxQwn)##递归读取取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!`)}}````#写操作````/*!*写**版权所有(c)2014-2015,JonSchlinkert。*根据麻省理工学院许可证获得许可。*/'usestrict';varfs=require('fs');varpath=require('path');varmkdir=require('mkdirp');/***将文件异步写入磁盘。如果它们尚不存在,则创建任何中间*目录。**```js*varwriteFile=require('write');*writeFile('foo.txt','这是要写的内容。',function(err){*if(err)console.log(err);*});*```**@namewriteFile*@param{String}`dest`目标文件路径*@param{String}`str`要写入磁盘的字符串。*@param{Function}`callback`*@apipublic*/module.exports=functionwriteFile(dest,str,cb){vardir=path.dirname(dest);fs.exists(目录,函数(存在){如果(存在){fs.writeFile(dest,str,cb);}else{mkdir(dir,function(err){if(err){returncb(err);}else{fs.writeFile(dest,str,cb);}});}});};/***将文件同步写入磁盘。如果它们尚不存在,则创建任何中间*目录。**```js*varwriteFile=require('write');*writeFile.sync('foo.txt','这是要写入的内容。');*```**@namewriteFile.sync*@param{String}`dest`目标文件路径*@param{String}`str`要写入磁盘的字符串。*@apipublic*/module.exports.sync=functionwriteFileSync(dest,str){vardir=path.dirname(dest);如果(!fs.existsSync(dir)){mkdir.sync(dir);}fs.writeFileSync(dest,str);};/***使用`fs.createWriteStream`,但也会创建任何中间*目录(如果它们尚不存在)。**```js*varwrite=require('write');*write.stream('foo.txt');*```**@namewriteFile.stream*@param{String}`dest`目标文件路径*@return{Stream}返回写入流。*@apipublic*/module.exports.stream=functionwriteFileStream(dest){vardir=path.dirname(dest);如果(!fs.existsSync(dir)){mkdir.sync(dir);}returnfs.createWriteStream(dest);};````#使用webpack构建文件删除项目时,每次都会生成一个dist目录下,有时需要删除dist目录下的所有旧文件。除了使用rm-rf/dist/命令删除外,还可以使用rimraf/dist/命令。rm-rf`命令用于删除文件和文件夹,不管文件夹是否为空,本地安装都可以删除:npminstallrimraf--save-dev全局安装:npminstallrimraf-g使用:rimraf\[...\]api:rimraf(f,\[opts\],callback)也可以使用打包包-delhttps://github.com/sindresorhus/del/blob/master/index.js#遍历文件https://github.com/ks3sdk/ks3-nodejs-sdk/blob/master/lib/util.js/**遍历文件*/functionwalkFile(p,opt,fileList){varfileList=文件列表||[];var_config={isDeep:false,ignore:/\s/ig};vardirList=fs.readdirSync(p);for(varitinopt){_config[it]=opt[it];}dirList。前面ach(function(item){if(!_config.ignore.test(item)){if(_config.isDeep){if(fs.statSync(p+'/'+item).isDirectory()){fileList.push(p+'/'+item);walkFile(p+'/'+item,opt,fileList);}else{fileList.push(p+'/'+item);}}else{fileList.push(p+'/'+item);}}});returnfileList;}#遍历文件夹https://github.com/ks3sdk/ks3-nodejs-sdk/blob/master/lib/util.js/**遍历文件夹*/functionwalkDir(p,opt){varfileList=walkFile(p,opt);var目录列表=[];fileList.forEach(function(item){if(fs.statSync(item).isDirectory()){dirList.push(item);}});returndirList;}#为文件夹下的文件加密md5/*生成md5对于导出的文件*/varfs=require('fs');varcrypto=require('crypto');varrootPath='../output/myapp/';varmd5File='md5conf.json';vartrimStr='myapp';varremoveReg=newRegExp('/'+trimStr+'/','g');var文件=fs.readdirSync(rootPath);varmd5Info={};//替换pathfiles.forEach(function(elem,i){varfilePath=rootPath+elem;varstat=fs.statSync(filePath);if(stat.isFile()){vardata=fs.readFileSync(filePath,'utf8');if(/^.*\.(css|js|html)/.test(elem)){console.log('replace',elem);varnewData=data.replace(removeReg,'');fs.writeFileSync(filePath,newData,'utf8');}}});//计算md5functioncalcMd5(path,files){files.forEach(function(elem,i){varfilePath=path+elem;varstat=fs.statSync(filePath);if(stat.isDirectory()){calcMd5(filePath+'/',fs.readdirSync(filePath));}else{vardata=fs.readFileSync(filePath);md5Info[filePath.replace(rootPath,'')]=crypto.createHash('md5').update(data).digest('hex');}});}calcMd5(rootPath,files);fs.writeFile(rootPath+md5File,JSON.stringify(md5Info));#常见的读写utilshttps://github.com/fex-team/fis3/blob/master/lib/util.js[https://github.com/yantze/fs-lockfile](https://github.com/yantze/fs-lockfile)#扩展包-[fs-extra](https://github.com/jprichardson/node-fs-extra)使用示例:https://github.com/1397467062/h5-react/blob/master/H5-react/multipage/scripts/build.js#参考https://www.jianshu.com/p/5683c8a93511【node命令行工具自动项目初始化的标准流程】(https://juejin.im/post/5d505356e51d456209238818?utm_source=gold_browser_extension)