node搜索文件夹下的指定内容

node搜索文件夹下的指定内容

执行效果

findString.js

var path = require("path");
var fs = require("fs");

var filePath = "./src";
var lookingForString = "add";

findString(filePath, lookingForString);

function findString(filePath, lookingForString) {
  recursiveReadFile(filePath);

  function recursiveReadFile(fileName) {
    if (!fs.existsSync(fileName)) return;
    if (isFile(fileName)) {
      check(fileName);
    }
    if (isDirectory(fileName)) {
      var files = fs.readdirSync(fileName);
      files.forEach(function(val, key) {
        var temp = path.join(fileName, val);
        if (isDirectory(temp)) recursiveReadFile(temp);
        if (isFile(temp)) check(temp);
      });
    }
  }
  function check(fileName) {
    var data = readFile(fileName);
    var exc = new RegExp(lookingForString);
    if (exc.test(data)) console.log(fileName);
  }
  function isDirectory(fileName) {
    if (fs.existsSync(fileName)) return fs.statSync(fileName).isDirectory();
  }
  function isFile(fileName) {
    if (fs.existsSync(fileName)) return fs.statSync(fileName).isFile();
  }
  function readFile(fileName) {
    if (fs.existsSync(fileName)) return fs.readFileSync(fileName, "utf-8");
  }
}

posted @ 2021-02-05 15:57  hello蔚蓝  阅读(530)  评论(0)    收藏  举报