parser.js 877 Bytes
/**
 * NDJSON 流解析器
 *
 * 处理 TCP 流中的换行分隔 JSON 消息
 */

class NDJSONParser {
  constructor() {
    this.buffer = '';
  }

  /**
   * 输入数据块,返回解析出的消息数组
   */
  parse(chunk) {
    this.buffer += chunk.toString();
    const lines = this.buffer.split('\n');
    this.buffer = lines.pop(); // 保留不完整的行

    const messages = [];
    for (const line of lines) {
      if (!line.trim()) continue;
      try {
        messages.push(JSON.parse(line));
      } catch (e) {
        // 非 JSON 行,作为原始输出
        messages.push({ _raw: true, content: line });
      }
    }
    return messages;
  }

  /**
   * 清空缓冲区
   */
  reset() {
    this.buffer = '';
  }

  /**
   * 获取剩余的缓冲区内容
   */
  getRemaining() {
    return this.buffer;
  }
}

module.exports = { NDJSONParser };