English

BunのBun.stdinで標準入力を読む方法

​​Bun​CLI,TypeScript

Bun では、await Bun.stdin.text() の1行で、パイプで渡された標準入力をまとめて文字列にできます。JSON なら await Bun.stdin.json() で、そのままオブジェクトになります。大きな入力は Bun.stdin.stream() で少しずつ読むと、1,000万行(約75MB)を合計したときの最大 RSS(プロセスが使った物理メモリの最大値)が、text() の 533.5MB から 34.4MB に下がりました。

cat data.json | bun script.ts や bun script.ts < input.txt のように、ほかのコマンドの出力やファイルを受け取って処理する CLI ツールを Bun で作るときの、読み方の選び方をまとめます。1行ずつ読む for await (const line of console) の書き方と、stream() で日本語が文字化けする落とし穴も、実際の出力で紹介します。

補足

検証環境は Ubuntu 24.04(x86_64、4コア、メモリ16GB)、Bun 1.4.4 です。入力はすべて、パイプ(|)またはファイルからのリダイレクト(<)で渡しました。端末からキーボードで打ち込む使い方、macOS と Windows、Node.js の process.stdin との比較は試していません。時間とメモリの数値は、この環境で3〜5回実行したときの中央値で、MB は 1024×1024 バイトとして計算しています。

まとめて読む text() と json()

公式ドキュメントのファイル入出力のページにあるとおり、Bun.stdin は Bun.file() と同じ BunFile で、読み取り専用です。そのため、ファイルと同じ text()、json() などで読めます。

ts
// text.ts
const text = await Bun.stdin.text();
console.log(`受け取った文字数: ${text.length}`);
console.log(JSON.stringify(text));
text
$ printf 'hello\nworld\n' | bun text.ts
受け取った文字数: 12
"hello\nworld\n"

最後の改行も含めて、そのまま文字列になります。何も渡さない場合(< /dev/null)は、空の文字列 "" が返りました。

JSON を受け取るなら json() です。

ts
// json.ts
const data = await Bun.stdin.json();
console.log(data.name, data.items.length);
text
$ echo '{"name":"neko","items":[1,2,3]}' | bun json.ts
neko 3
$ echo 'not json' | bun json.ts
SyntaxError: JSON Parse error: Unexpected identifier "not"

Bun v1.4.4 (Linux x64)

JSON として読めない入力では SyntaxError になり、終了コードは 1 でした。

入力が終わるまで待ち、2回目は空になる

text() が値を返すのは、入力の終わり(EOF)が来てからです。1行目を送ってから1秒後に2行目を送ると、2行目まで待ってからまとめて返りました。

ts
// wait.ts
const t0 = performance.now();
const text = await Bun.stdin.text();
console.log(`${Math.round(performance.now() - t0)}ms 後に受け取り: ${JSON.stringify(text)}`);
text
$ (printf 'a\n'; sleep 1; printf 'b\n') | bun wait.ts
998ms 後に受け取り: "a\nb\n"

また、標準入力は一度読むと残りません。seq 1 200000 > nums.txt で作った1,288,895バイトのファイルを渡し、text() を2回続けて呼んでみました。

ts
// twice2.ts(2回読むスクリプト)
const a = await Bun.stdin.text();
const b = await Bun.stdin.text();
console.log(`1回目: ${a.length} 文字 / 2回目: ${b.length} 文字`);
text
$ cat nums.txt | bun twice2.ts
1回目: 1288895 文字 / 2回目: 0 文字

2回目は0文字でした。ファイルからリダイレクトした場合(bun twice2.ts < nums.txt)も同じで、読み直すことはできませんでした。読んだ文字列を何度も使うなら、1回目の結果を変数に入れておきます。

少しずつ読む stream()

公式ガイドの標準入力のページでは、大きな入力を少しずつ読むには Bun.stdin.stream() を使うと紹介されています。返ってくるのは ReadableStream で、for await で回すと Uint8Array のかたまり(チャンク)が届きます。

同じページに「チャンクは行ごとに分かれるとは限らない」と書かれているので、パイプに書き込む側で、間を空けて少しずつ送って確かめました。ここでは入力が英数字だけなので、チャンクごとに文字列にしています(日本語の場合は後で説明します)。

ts
// show.ts
const t0 = performance.now();
for await (const chunk of Bun.stdin.stream()) {
  console.log(`${Math.round(performance.now() - t0)}ms: ${JSON.stringify(new TextDecoder().decode(chunk))}`);
}
text
$ (printf 'hel'; sleep 0.5; printf 'lo\nwor'; sleep 0.5; printf 'ld\n') | bun show.ts
0ms: "hel"
498ms: "lo\nwor"
1000ms: "ld\n"

チャンクは、送られてきた単位で届きました。"hel" のように行の途中で切れることもあります。text() と違い、入力の終わりを待たずに処理を始められます。

チャンクの大きさは、入力の渡し方で変わりました。数と大きさを数える次のスクリプトに、さきほどの nums.txt(1,288,895バイト)を渡した結果です。

ts
// chunks.ts
let n = 0, total = 0;
const sizes: number[] = [];
for await (const chunk of Bun.stdin.stream()) {
  n++; total += chunk.byteLength; sizes.push(chunk.byteLength);
}
console.log(`チャンク数: ${n} / 合計: ${total} バイト`);
console.log(`先頭5個のサイズ: ${sizes.slice(0,5).join(", ")}`);
console.log(`最大: ${Math.max(...sizes)} / 最小: ${Math.min(...sizes)}`);
渡し方 チャンク数 チャンクの大きさ
cat nums.txt | bun chunks.ts(パイプ) 20 最大 65,536 バイト
bun chunks.ts < nums.txt(リダイレクト) 3 262,144〜524,288 バイト

渡し方の違いは Bun.stdin.size にも出ました。パイプでは Infinity、リダイレクトではファイルの大きさ(1288895)です。パイプで渡されると Infinity になるので、入力の大きさを前もって知る用途には使えません。

日本語は TextDecoderStream を通してから文字列にする

公式ガイドの例では、チャンクを Buffer.from(chunk).toString() で文字列にしています。この書き方のまま、「ねこ」を10万回並べた600,000バイトの UTF-8 の入力をパイプで渡すと、文字化けが起きました。

ts
// naive.ts
let out = "";
let n = 0;
for await (const chunk of Bun.stdin.stream()) {
  n++;
  out += Buffer.from(chunk).toString();
}
const broken = (out.match(/\uFFFD/g) ?? []).length;
console.log(`チャンク数: ${n} / 文字数: ${out.length} / 化けた文字(U+FFFD): ${broken}`);
text
$ cat ja.txt | bun naive.ts
チャンク数: 10 / 文字数: 200009 / 化けた文字(U+FFFD): 15

20万文字のはずが 200,009 文字になり、置き換え文字(U+FFFD、画面では「�」)が15個入りました。「ね」「こ」は UTF-8 で1文字3バイトなので、チャンクの境目が文字の途中に来ると、前後のチャンクを別々に文字列にしたときに、その文字が壊れます。

そこで、バイトのストリームを文字列のストリームに変える TextDecoderStream を pipeThrough() で間に挟みます。同じ入力で、文字化けは0個になりました。

ts
// decoder.ts
let out = "";
let n = 0;
const decoded = Bun.stdin.stream().pipeThrough(new TextDecoderStream());
for await (const text of decoded) {
  n++;
  out += text;
}
const broken = (out.match(/\uFFFD/g) ?? []).length;
console.log(`チャンク数: ${n} / 文字数: ${out.length} / 化けた文字(U+FFFD): ${broken}`);
text
$ cat ja.txt | bun decoder.ts
チャンク数: 10 / 文字数: 200000 / 化けた文字(U+FFFD): 0
注意

Buffer.from(chunk).toString() の代わりに new TextDecoder().decode(chunk) でチャンクごとに文字列にしても、同じ入力で置き換え文字が15個入りました。

1行ずつ読む for await (const line of console)

公式ドキュメントの console のページによると、Bun の console は、標準入力を1行ずつ返す AsyncIterable でもあります。行に分ける処理を自分で書かずに済みます。

ts
// lines.ts
let i = 0;
for await (const line of console) {
  i++;
  console.log(`${i}: ${line}`);
}
console.log(`合計 ${i} 行`);

試すと、入力の最後が改行で終わっているときに、最後に空の行が1つ届きました。

text
$ printf 'a\nb\n' | bun lines.ts
1: a
2: b
3: 
合計 3 行

printf 'a\nb\n\nc' のように途中に空行がある入力では、空行もそのまま空の文字列として届きます。改行が \r\n(Windows の形式)の入力では、line の最後に \r が残りました。次のように空の行を飛ばし、trimEnd() で \r を取ると、printf 'a\r\nb\r\n' の入力から "a" と "b" だけが得られました。

ts
// lines-trim.ts
for await (const line of console) {
  if (!line) continue;
  console.log(JSON.stringify(line.trimEnd()));
}

公式ドキュメントにある足し算の例を、メッセージだけ日本語にして試しました。

ts
// adder.ts
console.log("足し算をします。数字を1行ずつ入力してください");
console.write("合計: 0\n> ");

let count = 0;
for await (const line of console) {
  count += Number(line);
  console.write(`合計: ${count}\n> `);
}

5 を3行パイプで渡すと、最後の空の行が Number("")、つまり 0 として足され、「合計: 15」が2回出ました。

text
$ printf '5\n5\n5\n' | bun adder.ts
足し算をします。数字を1行ずつ入力してください
合計: 0
> 合計: 5
> 合計: 10
> 合計: 15
> 合計: 15
> 

大きな入力での速さとメモリ

1行に1つの数を書いた入力を、3つの方法で読んで合計しました。text() は全部読んでから split("\n") で分け、stream() は TextDecoderStream を通したうえで、行の途中で切れた残りを次のチャンクにつなぐ書き方です。

ts
// sum-stream.ts
const t0 = performance.now();
let sum = 0, n = 0, rest = "";
for await (const text of Bun.stdin.stream().pipeThrough(new TextDecoderStream())) {
  const lines = (rest + text).split("\n");
  rest = lines.pop()!;
  for (const line of lines) { if (line) { sum += Number(line); n++; } }
}
if (rest) { sum += Number(rest); n++; }
console.log(`stream: ${n} 行 / 合計 ${sum.toLocaleString("en-US")} / ${Math.round(performance.now() - t0)} ms`);

最大 RSS は、bun --preload ./rss.ts sum-stream.ts のように、終了時に Linux の /proc/self/status にある VmHWM を出すファイルを先に読み込ませて測りました。3つとも合計は同じ値になっています。時間は、スクリプトの中で performance.now() で測った読み込みと合計の時間で、Bun の起動時間は含みません。100万行は5回、1,000万行は3回実行した中央値です。

読み方 100万行(約6.6MB)の時間 1,000万行(約75MB)の時間 1,000万行の最大 RSS
Bun.stdin.text() 111ms 1,080ms 533.5MB
Bun.stdin.stream() 127ms 1,226ms 34.4MB
for await … of console 396ms 4,335ms 32.6MB
3つの読み方で1,000万行を合計したときの最大RSSと時間の棒グラフ。最大RSSはtext()が533.5MB、stream()が34.4MB、consoleが32.6MB。時間はtext()が1,080ms、stream()が1,226ms、consoleが4,335ms
1,000万行(約75MB)を合計したときの最大RSSと時間(3回の中央値)

text() は速い代わりに、約75MB の入力で最大 RSS が500MB を超えました。stream() は text() より1割余り遅いだけで、メモリは約15分の1です。console で1行ずつ読む書き方はメモリは少ないものの、この環境では stream() の3倍以上の時間がかかりました。

ポイント

数MB 程度までの入力なら text() や json() でまとめて読むのが簡単です。入力の大きさが分からないときや、届いた順に処理したいときは、stream() に TextDecoderStream を通して読みます。公式ドキュメントの足し算の例のように、1行ずつ受け取って応える処理なら for await (const line of console) が手軽です。

​Posted by 86