批量修改目录,文件名
var fs = require('fs'); var path=require('path'); var dir= "E:/exam"; //path.dirname("D:/0228/"); console.log(dir); var state =fs.lstatSync(dir) if(!state.isDirectory()) { console.log("请输入目录") } var dirNameList=[]; var fileList=[]; getDirNames(dir,dirNameList); //replace(fileList) replaceFileName(fileList) function replaceFileName(fileList){ fileList.sort(function(a, b){ return b.length - a.length; }); console.log(fileList); for(let i =0;i<fileList.length;++i){ let fileName = fileList[i]; let item =fileName.split("\\").slice(-1); //console.log(item); if(item[0].toLowerCase().indexOf("zhaomin03")>=0){ let arr=fileName.split(path.sep); arr.pop(); let dirnew = arr.join(path.sep); fs.renameSync(fileName, path.join(dirnew,item[0].replace("zhaomin03","Wangbo03"))); fs.renameSync(fileName, path.join(dirnew,item[0].replace("Zhaomin03","Wangbo03"))); } } } function replace(dirNameList){ dirNameList.sort(function(a, b){ // ASC -> a.length - b.length // DESC -> b.length - a.length return b.length - a.length; }); console.log(dirNameList); for(let i =0;i<dirNameList.length;++i){ let folder = dirNameList[i]; let item =folder.split("\\").slice(-1); //console.log(item); if(item[0].toLowerCase().indexOf("zhaomin03")>=0){ let arr=folder.split(path.sep); arr.pop(); let dirnew = arr.join(path.sep); fs.renameSync(folder, path.join(dirnew,item[0].replace("zhaomin03","Wangbo03"))); fs.renameSync(folder, path.join(dirnew,item[0].replace("Zhaomin03","Wangbo03"))); } } } function getDirNames(dir,dirNameList){ var files = fs.readdirSync(dir); for(var i=0;i<files.length;++i){ var item =files[i]; var state =fs.lstatSync(path.resolve(dir,item)) if(state.isDirectory()){ dirNameList.push(path.resolve(dir,item)); //console.log(dirNameList); getDirNames(path.resolve(dir,item),dirNameList) }else{ fileList.push(path.join(dir,item)); } } }