node使用fs模块批处理更改文件名

node使用fs模块批处理更改文件名

talk is cheap, show me the code


//  引入fs和path模块
var fs = require('fs') 
var path = require('path')

// 找到文件的绝对地址
const directory = path.resolve(__dirname, './Flags')

function rename() {
    
    
  var thatfs = fs
  // 读取目录中的所有文件
  var imgArr = thatfs.readdirSync(directory, (err, files) => {
    
    
    return files
  })
	// 遍历文件(因为我的目录里有隐藏文件, 所以写成以下格式)
    for(let item of imgArr) {
    
    
      if(item.indexOf("_") >1 && item !== '.DS_Store'){
    
    
      // 我的业务逻辑是, 把文件后面的英文删除, 只保留中文. 中国_China.png ⇒ 中国.png
      var finalItem = item.split('_')[0]+'.png'
      console.log(item);
      // 更改文件名
      thatfs.renameSync(path.resolve(directory,item), path.resolve(directory,finalItem), err=> {
    
    
        console.log(err);
      } )
    }
  }
  
}
rename()

猜你喜欢

转载自blog.csdn.net/weixin_40944062/article/details/107367118