You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js在多个TXT文件中搜索关键词并返回上下行?

Node.js实现多TXT文件关键词搜索(含上下文行)

实现思路

  • 遍历指定目录下所有.txt格式文件
  • 逐文件读取内容并按行分割
  • 检索每行是否包含目标关键词,匹配时提取**上一行(若存在)、当前行、下一行(若存在)**作为结果
  • 按文件维度整理并输出匹配结果

完整实现代码

const fs = require('fs');
const path = require('path');

/**
 * 在指定目录的所有txt文件中搜索关键词,返回匹配行及上下行
 * @param {string} targetDir - 目标目录路径
 * @param {string} keyword - 要搜索的关键词
 * @returns {Object} 按文件名分组的匹配结果
 */
function searchTxtFilesWithContext(targetDir, keyword) {
  const results = {};
  const files = fs.readdirSync(targetDir).filter(file => path.extname(file).toLowerCase() === '.txt');

  files.forEach(file => {
    const filePath = path.join(targetDir, file);
    const content = fs.readFileSync(filePath, 'utf8');
    const lines = content.split('\n').map(line => line.trimEnd()); // 去除行尾换行符
    const fileMatches = [];

    lines.forEach((line, index) => {
      if (line.includes(keyword)) {
        const matchGroup = {};
        // 处理上一行
        if (index > 0) {
          matchGroup.previousLine = lines[index - 1];
        }
        matchGroup.currentLine = line;
        // 处理下一行
        if (index < lines.length - 1) {
          matchGroup.nextLine = lines[index + 1];
        }
        fileMatches.push(matchGroup);
      }
    });

    if (fileMatches.length > 0) {
      results[file] = fileMatches;
    }
  });

  return results;
}

// 使用示例
const searchDir = './txt-files'; // 替换为你的目标目录
const searchKeyword = 'Ships'; // 替换为你的关键词
const searchResults = searchTxtFilesWithContext(searchDir, searchKeyword);

// 打印结果
console.log('搜索结果:');
Object.entries(searchResults).forEach(([fileName, matches]) => {
  console.log(`\n=== 文件:${fileName} ===`);
  matches.forEach((match, idx) => {
    console.log(`匹配项 ${idx + 1}:`);
    if (match.previousLine) console.log(`上一行:${match.previousLine}`);
    console.log(`当前行:${match.currentLine}`);
    if (match.nextLine) console.log(`下一行:${match.nextLine}`);
  });
});

注意事项

  • 上述代码使用同步读取方式,适合处理小体积文本文件;若需处理大文件,建议改用fs.createReadStream流式读取,避免内存占用过高
  • 默认文件编码为utf8,若你的文本文件使用其他编码(如gbk),需在readFileSync中指定对应编码参数
  • 关键词匹配区分大小写,若需忽略大小写,可将判断逻辑改为line.toLowerCase().includes(keyword.toLowerCase())

内容的提问来源于stack exchange,提问作者Facu Gallardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:25:03