严格(默认)
🌐 Strict (default)
严格模式会捕捉“发了就忘”的模式,即生产者调用 write() 而不等待,这会导致内存无限增长。它把缓冲区限制为 budget 字节,并且将待写入队列限制为单个条目。
🌐 Strict mode catches "fire-and-forget" patterns where the producer calls
write() without awaiting, which would cause unbounded memory growth.
It limits the buffer to budget bytes and the pending writes queue
to a single entry.
如果你正确地等待每一次写入,你一次只能有一个未完成的写入(你自己的),所以你永远不会达到未完成写入的限制。未等待的写入会在待处理队列中积累,并在队列溢出时抛出异常:
🌐 If you properly await each write, you can only ever have one pending write at a time (yours), so you never hit the pending writes limit. Unawaited writes accumulate in the pending queue and throw once it overflows:
import { push, text } from 'node:stream/iter';
const { writer, readable } = push({ budget: 16384 });
// Consumer must run concurrently -- without it, the first write
// that fills the buffer blocks the producer forever.
const consuming = text(readable);
// GOOD: awaited writes. The producer waits for the consumer to
// make room when the buffer is full.
for (const item of dataset) {
await writer.write(item);
}
await writer.end();
console.log(await consuming);const { push, text } = require('node:stream/iter');
async function run() {
const { writer, readable } = push({ budget: 16384 });
// Consumer must run concurrently -- without it, the first write
// that fills the buffer blocks the producer forever.
const consuming = text(readable);
// GOOD: awaited writes. The producer waits for the consumer to
// make room when the buffer is full.
for (const item of dataset) {
await writer.write(item);
}
await writer.end();
console.log(await consuming);
}
run().catch(console.error);忘记 await 最终会抛出:
🌐 Forgetting to await will eventually throw:
// BAD: fire-and-forget. Strict mode throws once both buffers fill.
for (const item of dataset) {
writer.write(item); // Not awaited -- queues without bound
}
// --> throws "Backpressure violation: too many pending writes"