const fs = require('fs'); const path=require('path'); //遍历文件 function travel(dir,callback){ fs.readdirSync(dir).forEach((file)=>{ var pathname=path.join(dir,file) if(fs.statSync(pathname).isDirectory()){ travel(pathname,callback) }else{ callback(pathname) } }) } var fileArr=[] //获取文件路径合集 travel('D:/CloudMusicDownload',function(pathname){ console.log(pathname) fileArr.push(pathname) }) console.log(fileArr.length) //使用rename 移动文件 fileArr.forEach((path)=>{ let oldPath = path.replace(/\\/g,"/") let filename = oldPath.slice(oldPath.lastIndexOf('/')+1,oldPath.length) let newPath = `D:/music/${filename}` console.log(filename) fs.rename(oldPath,newPath,function (err) { if (err) throw err; console.log('renamed complete'); }); })