前言受疫情影响,最近一直在家办公。我遇到了一个问题。同事本来需要按照清单给我提供一些文件,但是看了之后发现少了很多。所以我需要根据列表向他提供当前丢失文件的名称,并让他向我提供丢失的文件。但是因为文件比较多,没办法一一比较,所以想用node写个脚本来做这个,就这样吧。ps:如果要用node扫描文件夹下的所有文件(不同目录层级),请直接进行第5步。解决方法1.先准备好文件,将已有的文件放在一个文件夹中。由于所有的文件都在不同的目录下,以后阅读起来可能会有点麻烦。2、然后整理出文件列表,存入LIST中。3、其实我们不需要key,我们只需要使用下面的地址,所以Object.values()方法把后面的value取出来存入数组,执行下面看结果:让apiList=Object.values(ENV);console.log(apiList)4.获取到的地址中,https开头的我们不需要。我们读取以http开头的文件并将它们存储在一个数组中:lethttp=[]for(letitemofapiList){if(item.substr(0,5)=="https"){https.push(item)}else{http.push(item)}}5.接下来进入最关键的地方,我们需要把文件夹下的所有文件都读取出来,但是文件的路径层级不同,所以需要使用递归调用来获取。constfs=require('fs')constbasePath='./src/assets/dummyAPIResponse'varjoin=require('path').join;让fileList=[]函数getJsonFiles(jsonPath){让jsonFiles=[];functionfindJsonFile(path){letfiles=fs.readdirSync(path);files.forEach(function(item,index){letfPath=join(path,item);letstat=fs.statSync(fPath);if(stat.isDirectory()===true){findJsonFile(fPath);}如果(stat.isFile()===true){jsonFiles.push(item);}});}findJsonFile(jsonPath);fileList=jsonFiles}getJsonFiles(basePath);console.log(fileList)6.此时我们已经获取了所有的文件名和名称列表,我们需要对两个名称进行比较,得到重复的名称列表(即existing),然后比较existing和full名称列表以获取丢失的文件名。letoutput=[]for(letitemoffileList){for(lethttpItemofhttp){if(httpItem.indexOf(item)!==-1){output.push(httpItem)}}}functiongetArrDifference(arr1,arr2){returnarr1.concat(arr2).filter(function(v,i,arr){returnarr.indexOf(v)===arr.lastIndexOf(v);});}letresult=getArrDifference(输出,http)console.log(result)7.这个时候我们的任务还有点短。让我们创建另一个文件并使用节点将数据写入其中。fs.writeFileSync('./file/http.js',结果,{编码:"UTF-8"});总结一下其实用到很多node和js知识的简单功能,比如读取文件名和路径,比较数组等,这篇文章先写这么多,以后慢慢写。最后贴出本文所有代码,供大家参考。让apiList=Object.values(ENV);lethttp=[]for(letitemofapiList){if(item.substr(0,5)!="https"){http.push(item)}}constfs=require('fs')constbasePath='./src/assets/dummyAPIResponse'varjoin=require('path').join;让fileList=[]函数getJsonFiles(jsonPath){让jsonFiles=[];functionfindJsonFile(path){letfiles=fs.readdirSync(path);files.forEach(function(item,index){letfPath=join(path,item);letstat=fs.statSync(fPath);if(stat.isDirectory()===true){findJsonFile(fPath);}如果(stat.isFile()===true){jsonFiles.push(item);}});}findJsonFile(jsonPath);fileList=jsonFiles}getJsonFiles(basePath);letoutput=[]for(letitemoffileList){for(lethttpItemofhttp){if(httpItem.indexOf(item)!==-1){output.push(httpItem)}}}functiongetArrDifference(arr1,arr2){returnarr1.concat(arr2).filter(function(v,i,arr){returnarr.indexOf(v)===arr.lastIndexOf(v);});}letresult=getArrDifference(output,http)console.log(result);fs.writeFileSync('./file/http.js',result,{encoding:"UTF-8"});
