1. 程式人生 > >node 統計指定目錄 檔案、檔案夾個數、列印詳細內容 且最後一次列印 同時替換掉檔案指定內容

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 ')); })