This article introduces NodeJs regular keyword search directory files, including NodeJs regular keyword search directory files and search files containing keywords using examples, application skills, basic knowledge summary and matters needing attention.

Requirements:

Keyword search project output related methods. Example: Search for the entire keyword, such as looking for the interface starting with/IPo-chains/and then summarize all the results.

Technical points:

NodeJs traverses directories, reads files, matches regular keywords, and returns an array of conditions.

Code:

var fs = require("fs"); const resultArr = []; // route const filePath = path.resolve('./ SRC '); // const lookingForString = / Ipos - Chains \/.*? (? =')/g; recursiveReadFile(filePath); const newArr = [...new Set(resultArr)]; The console. The log (' data -- - > 'newArr); // console.log('data -->', json.stringify (newArr)); 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); const arr = data.match(exc); if(! arr)return; resultArr.push(... arr); } 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"); }Copy the code

Node xiaobai, welcome to learn and communicate.