示例工程 41-sidecar-child-process

41-sidecar-child-process/demo-01-ndjson/ndjson.ts

typescript · 1.3 KB

type Decoded = { lines: unknown[]; rest: string; errors: string[] };

function decode(buffer: string, chunk: string): Decoded {
  const combined = buffer + chunk;
  const parts = combined.split("\n");
  const rest = parts.pop() ?? "";
  const lines: unknown[] = [];
  const errors: string[] = [];
  for (const part of parts) {
    const line = part.trim();
    if (!line) continue;
    try {
      lines.push(JSON.parse(line));
    } catch (error) {
      errors.push(error instanceof Error ? error.message : String(error));
    }
  }
  return { lines, rest, errors };
}

const first = decode("", '{"type":"ready","pid":1}\n{"type":"heart');
const second = decode(first.rest, 'beat","seq":1}\n');
const multiple = decode(
  "",
  '{"id":1,"result":17984}\n{"id":2,"result":17984}\n',
);
const bad = decode("", '{"type":"ready"}\nnot-json\n');

const ok =
  first.lines.length === 1 &&
  (first.lines[0] as { type?: string }).type === "ready" &&
  first.rest === '{"type":"heart' &&
  second.lines.length === 1 &&
  (second.lines[0] as { type?: string }).type === "heartbeat" &&
  second.rest === "" &&
  multiple.lines.length === 2 &&
  bad.lines.length === 1 &&
  bad.errors.length === 1;

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    first,
    second,
    multiple,
    bad,
  }),
);