Skip to content

Instantly share code, notes, and snippets.

@AtWhuhu
Created August 14, 2020 06:51
Show Gist options
  • Save AtWhuhu/ad5ee83c5bf5d171e4b99afc2e47cafe to your computer and use it in GitHub Desktop.
Save AtWhuhu/ad5ee83c5bf5d171e4b99afc2e47cafe to your computer and use it in GitHub Desktop.
遍历文件并移动
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');
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment