Skip to content

Getting Started

Install

bash
npm install claude-code-parser

Quick Start

typescript
import { spawn } from 'child_process'
import { createInterface } from 'readline'
import { parseLine, Translator, createMessage } from 'claude-code-parser'

// 1. Spawn Claude Code in stream-json mode
const claude = spawn('claude', [
  '-p',
  '--input-format', 'stream-json',
  '--output-format', 'stream-json',
  '--verbose',
], { stdio: ['pipe', 'pipe', 'inherit'] })

// 2. Create a translator (handles dedup automatically)
const translator = new Translator()

// 3. Parse stdout line by line
const rl = createInterface({ input: claude.stdout! })
rl.on('line', (line) => {
  const event = parseLine(line)
  if (!event) return

  for (const relay of translator.translate(event)) {
    switch (relay.type) {
      case 'text_delta':
        process.stdout.write(relay.content)
        break
      case 'tool_use':
        console.log(`\n[tool] ${relay.toolName}`)
        break
      case 'turn_complete':
        console.log(`\n[done] $${relay.costUsd?.toFixed(4)}`)
        break
    }
  }
})

// 4. Send a message via stdin
claude.stdin!.write(createMessage.user('What is 2 + 2?'))

What This Library Does

Three things:

  1. parseLine() — Takes a single NDJSON line string, returns a typed ClaudeEvent or null
  2. Translator — Converts raw events into deduplicated RelayEvent objects (handles --verbose cumulative snapshots and multi-agent interleaving)
  3. createMessage — Constructs NDJSON messages for Claude Code's undocumented stdin protocol

What This Library Does NOT Do

  • Does not spawn or manage Claude Code processes (use the official SDK for that)
  • Does not handle WebSocket, HTTP, or any transport
  • Does not render any UI

You bring the NDJSON stream. This library parses it.

When to Use This vs the Official SDK

ScenarioUse
Spawn Claude Code and get resultsOfficial SDK (@anthropic-ai/claude-code)
Build a WebSocket relay / custom frontendThis library
Parse saved NDJSON log filesThis library
Build a browser-based viewerThis library
CI script extracting cost/tokensThis library
Custom transport (gRPC, IPC, etc.)This library

Not affiliated with or endorsed by Anthropic.