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

如何用Node.js通过流按条件向文件追加指定注解

基于Node.js流实现Java文件注解自动追加

直接上完整实现代码,解决你用流处理文件时的检查与追加需求:

const fs = require('fs');

async function appendCircuitAnnotation() {
  const inputPath = './File/controller.java';
  const outputPath = './FileUpload/auditcontroller_test.java';
  const targetMethod = 'createEvent';
  const annotation = '@Circuit(name = "backendB")'; // 修正注解格式,Java注解不需要外层括号

  // 状态跟踪变量
  let hasFoundMethod = false;
  let hasAnnotation = false;
  let buffer = ''; // 处理跨块的内容残留

  const readStream = fs.createReadStream(inputPath, 'utf8');
  const writeStream = fs.createWriteStream(outputPath);

  readStream.on('data', (chunk) => {
    buffer += chunk;

    // 先检查是否已经存在目标注解
    if (!hasAnnotation) {
      const annotationRegex = new RegExp(`\\s*${annotation}\\s*`, 'g');
      if (annotationRegex.test(buffer)) {
        hasAnnotation = true;
        writeStream.write(buffer);
        buffer = '';
        return;
      }
    }

    // 检查是否存在目标方法,且未添加注解
    if (!hasFoundMethod && !hasAnnotation) {
      // 匹配方法声明,兼容不同修饰符、返回值的情况
      const methodRegex = new RegExp(
        '(\\s*(public|private|protected)?\\s*\\w+\\s+)' + targetMethod + '\\s*\\(',
        'g'
      );
      let match;
      while ((match = methodRegex.exec(buffer)) !== null) {
        hasFoundMethod = true;
        // 保留方法前的缩进,保证代码格式一致
        const insertPos = match.index;
        const indent = buffer.slice(0, insertPos).match(/\s*$/)[0];
        const modifiedChunk = buffer.slice(0, insertPos) + indent + annotation + '\n' + buffer.slice(insertPos);
        writeStream.write(modifiedChunk);
        buffer = '';
        break;
      }
    }

    // 处理未匹配到目标内容的块,保留可能跨块的部分内容
    if (buffer && !hasFoundMethod && !hasAnnotation) {
      const lastNewLinePos = buffer.lastIndexOf('\n');
      if (lastNewLinePos !== -1) {
        writeStream.write(buffer.slice(0, lastNewLinePos + 1));
        buffer = buffer.slice(lastNewLinePos + 1);
      }
    }
  });

  readStream.on('end', () => {
    // 写入剩余的缓冲区内容
    if (buffer) {
      writeStream.write(buffer);
    }
    writeStream.end();
    console.log('文件处理完成');
  });

  // 流错误处理
  readStream.on('error', (err) => {
    console.error('读取文件出错:', err);
    writeStream.destroy();
  });

  writeStream.on('error', (err) => {
    console.error('写入文件出错:', err);
    readStream.destroy();
  });
}

// 执行处理函数
appendCircuitAnnotation();

关键实现说明

  • 状态跟踪:用hasFoundMethod和hasAnnotation两个变量避免重复处理,确保只在符合条件时插入注解。
  • 跨块兼容:通过buffer保存块末尾可能截断的内容(比如createEve),防止漏掉跨块的方法声明。
  • 精准匹配:正则表达式专门匹配Java方法声明,不会误匹配字符串中的createEvent,同时保留原有缩进保证代码格式。
  • 格式修正:你原代码中的注解外层括号是错误的,Java注解直接写@Circuit(name = "backendB")即可。

注意事项

  1. 如果createEvent有重载方法,需要调整正则表达式匹配特定方法签名。
  2. 处理前建议备份原文件,避免意外覆盖。
  3. 若注解可能出现在方法内部,需要修改检查逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:23:28