Getting Started
Install
bash
npm install claude-code-parserQuick 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:
parseLine()— Takes a single NDJSON line string, returns a typedClaudeEventornullTranslator— Converts raw events into deduplicatedRelayEventobjects (handles--verbosecumulative snapshots and multi-agent interleaving)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
| Scenario | Use |
|---|---|
| Spawn Claude Code and get results | Official SDK (@anthropic-ai/claude-code) |
| Build a WebSocket relay / custom frontend | This library |
| Parse saved NDJSON log files | This library |
| Build a browser-based viewer | This library |
| CI script extracting cost/tokens | This library |
| Custom transport (gRPC, IPC, etc.) | This library |