node.js批量修改图片名

   1: "use strict";
   2:  
   3: var fs = require('fs');
   4:  
   5: var args = process.argv.splice(2);
   6: var fileDirectory = args[0] || 'xxx';
   7:  
   8: if (fs.existsSync(fileDirectory)) {
   9:     var files = fs.readdirSync(fileDirectory);
  10:  
  11:     files.forEach(function(file) {
  12:         var filePath = fileDirectory + "/" + file;
  13:         
  14:         if (/\.jpg$/.test(file)) {
  15:             var fileName = file.replace(/(\-)(\d+)(\_s\.jpg)/, function() {    
  16:                 return arguments[1] + ((arguments[2] | 0) + 1714) + arguments[3];
  17:             });
  18:  
  19:             var newFilePath = fileDirectory + "/" + fileName;
  20:  
  21:             fs.rename(filePath, newFilePath, function(err) {
  22:                 if (err) throw err;
  23:  
  24:                 console.log(fileName + ' ok~');
  25:             });
  26:         }
  27:     });
  28:  
  29: } else {
  30:     console.log(fileDirectory + "  Not Found!");
  31: }

1、首先判断目录是否存在;

2、遍历目录,获取文件名;

3、使用rename方法修改文件名;

posted @ 2012-08-15 16:52  meteoric_cry  阅读(2124)  评论(0编辑  收藏  举报