欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js匹配文件夾所有文件關(guān)鍵字的完整教程

 更新時(shí)間:2025年04月30日 11:38:12   作者:楠木685  
本文基于nodejs構(gòu)建一個(gè)自動(dòng)化檢測(cè)工具:讀取 Excel 中的關(guān)鍵字,在指定目錄的所有文件中搜索是否存在對(duì)應(yīng)內(nèi)容,最終生成帶標(biāo)記結(jié)果的 Excel 文件,需要的朋友可以參考下

一、場(chǎng)景需求分析

典型應(yīng)用場(chǎng)景:

  • 前端接口冗余:檢測(cè)接口是否使用
  • 前端項(xiàng)目國(guó)際化:檢測(cè)翻譯詞庫(kù)是否已全部使用
  • 代碼規(guī)范檢查:驗(yàn)證廢棄 API 是否仍存在引用
  • 文檔完整性驗(yàn)證:確認(rèn)知識(shí)庫(kù)詞條是否都有對(duì)應(yīng)文檔

二、技術(shù)棧說(shuō)明

技術(shù)版本作用
Node.js>=14.x運(yùn)行環(huán)境
xlsx^0.18.5Excel 文件處理
fs/promises內(nèi)置文件系統(tǒng)操作
path內(nèi)置路徑處理

安裝依賴:

npm install xlsx

三、核心代碼解析

1. Excel讀取模塊

const xlsx = require("xlsx");

function readExcelRows(filePath) {
  const workbook = xlsx.readFile(filePath);
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];
  // header:1 表示保留二維數(shù)組結(jié)構(gòu)
  const rows = xlsx.utils.sheet_to_json(sheet, { header: 1 }); 
  return { workbook, sheetName, rows };
}

注意:sheet_to_json 的 header 參數(shù)決定輸出格式:

  • header:1 → 二維數(shù)組(保留原始行列結(jié)構(gòu))
  • header:["col1","col2"] → 對(duì)象數(shù)組(自動(dòng)映射字段)

2. 目錄遍歷模塊

async function getAllFilesContent(dirPath, fileList = []) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirPath, async (err, files) => {
      if (err) return reject(err);
      
      for (const file of files) {
        const fullPath = path.join(dirPath, file);
        const stats = fs.statSync(fullPath);
        
        if (stats.isDirectory()) {
          if (!excludedDirs.includes(file)) {
            await getAllFilesContent(fullPath, fileList);
          }
        } else if (stats.isFile()) {
          try {
            const content = fs.readFileSync(fullPath, "utf8");
            fileList.push({ path: fullPath, content });
          } catch (err) {
            console.error(`讀取文件失敗: ${fullPath}`);
          }
        }
      }
      resolve(fileList);
    });
  });
}

最佳實(shí)踐建議:

  • 使用 fs.statSync 判斷文件類型
  • 排除 node_modules 等無(wú)關(guān)目錄
  • 添加錯(cuò)誤處理防止程序崩潰

3. 匹配檢測(cè)邏輯

for (let i = 0; i < rows.length; i++) {
  const row = rows[i];
  const keyword = row[1]; // 取第二列數(shù)據(jù)
  
  if (typeof keyword === "string") {
    const matched = allFiles.some((file) => 
      file.content.includes(keyword)
    );
    
    if (!matched) {
      row[4] = "是"; // 在第五列標(biāo)記
    }
  }
}

性能優(yōu)化思路:

  • 使用正則表達(dá)式預(yù)編譯
  • 增加防抖機(jī)制處理超長(zhǎng)文本
  • 支持批量處理多個(gè)工作表

四、完整代碼

const fs = require("fs");
const path = require("path");
const xlsx = require("xlsx");

const excludedDirs = ["node_modules", "public"];

// 讀取 Excel 所有行(保留結(jié)構(gòu))
function readExcelRows(filePath) {
  const workbook = xlsx.readFile(filePath);
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];
  const rows = xlsx.utils.sheet_to_json(sheet, { header: 1 }); // 保持?jǐn)?shù)組結(jié)構(gòu)
  return { workbook, sheetName, rows };
}

// 獲取目錄下所有文件內(nèi)容
async function getAllFilesContent(dirPath, fileList = []) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirPath, async (err, files) => {
      if (err) return reject(err);

      for (const file of files) {
        const fullPath = path.join(dirPath, file);
        const stats = fs.statSync(fullPath);

        if (stats.isDirectory()) {
          if (!excludedDirs.includes(file)) {
            await getAllFilesContent(fullPath, fileList);
          }
        } else if (stats.isFile()) {
          try {
            const content = fs.readFileSync(fullPath, "utf8");
            fileList.push({ path: fullPath, content });
          } catch (err) {
            console.error(`讀取文件失敗: ${fullPath}`);
          }
        }
      }

      resolve(fileList);
    });
  });
}

// 主函數(shù)
async function main() {
  const excelPath = "./data.xlsx"; // 替換成你的 Excel 文件路徑
  const targetDir1 = ""; // 替換成你要查找的文件夾路徑
  const targetDir2 = "";// 替換成你要查找的文件夾路徑,可選多個(gè)路徑

  // 1. 讀取 Excel 原始行數(shù)據(jù)
  const { workbook, sheetName, rows } = readExcelRows(excelPath);
  console.log(`?? 共讀取 ${rows.length} 行`);

  // 2. 獲取兩個(gè)目錄的所有文件內(nèi)容
  const files1 = await getAllFilesContent(targetDir1);
  const files2 = await getAllFilesContent(targetDir2);
  const allFiles = [...files1, ...files2];
  console.log(`?? 共讀取 ${allFiles.length} 個(gè)文件`);

  // 3. 遍歷 Excel 每一行,檢查第2列關(guān)鍵詞是否被文件匹配
  for (let i = 0; i < rows.length; i++) {
    const row = rows[i];
    const keyword = row[1]; // 第二列

    if (typeof keyword === "string") {
      const matched = allFiles.some((file) => file.content.includes(keyword));
      if (!matched) {
        row[4] = "是"; // 第5列寫入“是”
      }
    }
  }

  // 4. 寫回新的 Excel 文件
  const newSheet = xlsx.utils.aoa_to_sheet(rows);
  const newWorkbook = xlsx.utils.book_new();
  xlsx.utils.book_append_sheet(newWorkbook, newSheet, sheetName);
  xlsx.writeFile(newWorkbook, "./test.xlsx");

  console.log(
    "? 處理完成,未匹配的關(guān)鍵詞已在第5列標(biāo)記“是”,結(jié)果已保存為 keywords_result.xlsx"
  );
}

main();

到此這篇關(guān)于Node.js匹配文件夾所有文件關(guān)鍵字的完整教程的文章就介紹到這了,更多相關(guān)Node.js匹配文件夾文件關(guān)鍵字內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論