node 统计指定目录 文件、文件夹个数、打印详细内容 且最后一次打印 同时替换掉文件指定内容

var fs = require('fs');

// count and  time
var count = {
  file: 0,
  fileArr:[],
  dir: 0,
  dirArr:[]
};
var timeStart = new Date();

function readDirRecur(folder, callback) {
  fs.readdir(folder, function (err, files) {
    if (!files.length) {
      return callback();
    }
    var countTime = 0;
    var checkEnd = function () {
      if (++countTime == files.length) {
        callback();
      }
    };

    files.forEach(function (file) {
      var fullPath = folder + '/' + file;

      fs.stat(fullPath, function (err, stats) {
        if (stats.isDirectory()) {
          readDirRecur(fullPath, checkEnd);
          count.dir++;
          count.dirArr.push(fullPath);
        } else {
          if (file[0] == '.') {

          } else {

            // replace
            fs.readFile(fullPath, 'utf8', function(err, data){
                var content = data.replace(/[^a-zA-Z]alert/ig,"xalert");
                fs.writeFile(fullPath, content, function (err) {
                    if (err) {
                        console.log('error');
                    } else {
                        console.log('year');
                    }
                });
            });


            count.file++;
            count.fileArr.push(fullPath);
          }
          checkEnd();
        }
      })
    })

  })
}

readDirRecur('E:/test/a', function (filePath) {
  console.log('done', new Date() - timeStart);
  console.log('');
  console.log('dir:' + count.dir);
  console.log(count.dirArr.join(' \n '));
  console.log('');
  console.log('file:' + count.file);
  console.log(count.fileArr.join(' \n '));
})

猜你喜欢

转载自www.cnblogs.com/justSmile2/p/10044367.html
今日推荐