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");
}
}
标签:node,function,fs,temp,fileName,isDirectory,文件夹,搜索,var 来源: https://www.cnblogs.com/Azune/p/14378216.html