Reading stdin with Bun.stdin in Bun
In Bun, one line, await Bun.stdin.text(), turns piped stdin into a string. For JSON, await Bun.stdin.json() returns an object directly. For large input, reading in pieces with Bun.stdin.stream() lowered the max RSS (the peak physical memory the process used) when summing 10 million lines (about 75 MB) from 533.5 MB with text() to 34.4 MB.
This article explains how to choose a reading method for a CLI tool written in Bun that takes the output of another command or a file, such as cat data.json | bun script.ts or bun script.ts < input.txt. It also shows, with actual output, the for await (const line of console) pattern for reading line by line, and the pitfall where stream() garbles Japanese text.
The test environment was Ubuntu 24.04 (x86_64, 4 cores, 16 GB RAM) with Bun 1.4.4. All input was passed through a pipe (|) or a file redirect (<). I did not test typing input at a terminal, macOS, Windows, or comparisons with Node.js's process.stdin. The time and memory figures are medians of 3 to 5 runs in this environment, and MB is computed as 1024×1024 bytes.
Reading all at once with text() and json()
As the official documentation on file I/O explains, Bun.stdin is a BunFile like the one returned by Bun.file(), and it is read-only. So you can read it with the same text(), json(), and other methods you use for files.
// text.ts
const text = await Bun.stdin.text();
console.log(`受け取った文字数: ${text.length}`);
console.log(JSON.stringify(text));
$ printf 'hello\nworld\n' | bun text.ts
受け取った文字数: 12
"hello\nworld\n"
The string includes the final newline as is. When nothing is passed (< /dev/null), it returned an empty string "".
If the input is JSON, use json().
// json.ts
const data = await Bun.stdin.json();
console.log(data.name, data.items.length);
$ 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)
When the input is not valid JSON, it throws a SyntaxError, and the exit code was 1.
Waits for end of input, and the second read is empty
text() returns a value only after the end of input (EOF) arrives. When I sent the first line, then the second line one second later, it waited until the second line arrived and then returned everything at once.
// wait.ts
const t0 = performance.now();
const text = await Bun.stdin.text();
console.log(`${Math.round(performance.now() - t0)}ms 後に受け取り: ${JSON.stringify(text)}`);
$ (printf 'a\n'; sleep 1; printf 'b\n') | bun wait.ts
998ms 後に受け取り: "a\nb\n"
Also, once stdin has been read, it does not come back. I created a 1,288,895-byte file with seq 1 200000 > nums.txt, passed it in, and called text() twice in a row.
// twice2.ts (script that reads twice)
const a = await Bun.stdin.text();
const b = await Bun.stdin.text();
console.log(`1回目: ${a.length} 文字 / 2回目: ${b.length} 文字`);
$ cat nums.txt | bun twice2.ts
1回目: 1288895 文字 / 2回目: 0 文字
The second read returned 0 characters. Redirecting from a file (bun twice2.ts < nums.txt) behaved the same way, and I could not read it again. If you need the text more than once, store the result of the first read in a variable.
Reading in chunks with stream()
The official guide on stdin introduces Bun.stdin.stream() for reading large input in pieces. It returns a ReadableStream, and iterating it with for await yields Uint8Array chunks.
The same page says that chunks do not necessarily split at line boundaries. To check this, I wrote to the pipe with pauses between writes. Since the input here is only alphanumeric, I converted each chunk to a string directly. (I explain the Japanese case later.)
// 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))}`);
}
$ (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"
Chunks arrived in the units they were sent. A chunk can also end partway through a line, as with "hel". Unlike text(), you can start processing without waiting for the end of input.
The chunk size depended on how the input was passed. I passed the same nums.txt (1,288,895 bytes) to this script, which counts chunks and their sizes.
// 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)}`);
| How it's fed | Chunk count | Chunk size |
|---|---|---|
cat nums.txt | bun chunks.ts (pipe) |
20 | Up to 65,536 bytes |
bun chunks.ts < nums.txt (redirect) |
3 | 262,144 to 524,288 bytes |
The way input was passed also showed up in Bun.stdin.size. With a pipe it was Infinity, and with a redirect it was the file size (1288895). Because a piped input reports Infinity, you cannot use it to know the input size in advance.
Decode Japanese through TextDecoderStream before making strings
The official guide's example converts each chunk with Buffer.from(chunk).toString(). When I piped in 600,000 bytes of UTF-8 made of the Japanese word for cat, "neko", repeated 100,000 times, using that same approach, the text was garbled.
// 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}`);
$ cat ja.txt | bun naive.ts
チャンク数: 10 / 文字数: 200009 / 化けた文字(U+FFFD): 15
The result was 200,009 characters instead of the expected 200,000, and 15 replacement characters (U+FFFD, shown as "�") appeared. In UTF-8, the two characters of neko, "ne" and "ko", are 3 bytes each. When a chunk boundary falls inside such a character, converting the neighboring chunks separately breaks that character.
So I inserted a TextDecoderStream, which turns a byte stream into a text stream, using pipeThrough(). With the same input, there were zero garbled characters.
// 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}`);
$ cat ja.txt | bun decoder.ts
チャンク数: 10 / 文字数: 200000 / 化けた文字(U+FFFD): 0
I also tried new TextDecoder().decode(chunk) to convert each chunk separately instead of Buffer.from(chunk).toString(). With the same input, it still produced 15 replacement characters.
Reading line by line with for await (const line of console)
According to the official documentation for console, Bun's console is also an AsyncIterable that yields stdin one line at a time. You do not need to write your own line-splitting code.
// lines.ts
let i = 0;
for await (const line of console) {
i++;
console.log(`${i}: ${line}`);
}
console.log(`合計 ${i} 行`);
When I tried it, an input that ended with a newline produced one extra empty line at the end.
$ printf 'a\nb\n' | bun lines.ts
1: a
2: b
3:
合計 3 行
With an input that has an empty line in the middle, such as printf 'a\nb\n\nc', the empty line also arrives as an empty string. When lines end with \r\n (the Windows format), a \r remained at the end of line. Using the following code, which skips empty lines and removes \r with trimEnd(), the input printf 'a\r\nb\r\n' produced only "a" and "b".
// lines-trim.ts
for await (const line of console) {
if (!line) continue;
console.log(JSON.stringify(line.trimEnd()));
}
I also tried the addition example from the official documentation, with only the messages changed to Japanese.
// 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> `);
}
When I piped three lines of 5, the final empty line was added as Number(""), which is 0, so the total 15 appeared twice.
$ printf '5\n5\n5\n' | bun adder.ts
足し算をします。数字を1行ずつ入力してください
合計: 0
> 合計: 5
> 合計: 10
> 合計: 15
> 合計: 15
>
Speed and memory with large input
I read input with one number per line and summed the numbers using three methods. text() reads everything first and then splits with split("\n"). stream() runs the input through TextDecoderStream and carries the partial line at the end of each chunk over to the next one.
// 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`);
To measure max RSS, I ran the script with bun --preload ./rss.ts sum-stream.ts, where rss.ts is loaded first and prints VmHWM from /proc/self/status on Linux at exit. All three methods produced the same total. Times are the read and sum times measured with performance.now() inside the script, so they exclude Bun's startup time. Each value is the median of 5 runs for 1 million lines and 3 runs for 10 million lines.
| Method | Time for 1 million lines (about 6.6 MB) | Time for 10 million lines (about 75 MB) | Max RSS for 10 million lines |
|---|---|---|---|
Bun.stdin.text() |
111 ms | 1,080 ms | 533.5 MB |
Bun.stdin.stream() |
127 ms | 1,226 ms | 34.4 MB |
for await … of console |
396 ms | 4,335 ms | 32.6 MB |

text() is fast, but with an input of about 75 MB its max RSS went over 500 MB. stream() was only a little over 10% slower than text(), and it used about one fifteenth of the memory. Reading line by line with console uses little memory, but in this environment it took more than three times as long as stream().
For inputs up to a few MB, reading everything at once with text() or json() is the simplest option. When you do not know the input size in advance, or you want to process data as it arrives, use stream() with TextDecoderStream. For processing that receives one line at a time and responds to each, such as the addition example in the official documentation, for await (const line of console) is the easiest choice.





