ondrain(drainable)
等待可排空的写入器恢复物理缓冲区容量。如果对象未实现可排空协议,则返回 null;或者返回一个承诺,当缓冲数据低于字节预算时,承诺会以 true 完成。
🌐 Wait for a drainable writer to regain physical buffer capacity. Returns null
if the object does not implement the drainable protocol, or a promise that
fulfills with true when buffered data falls below the byte budget.
对于使用 'drop-oldest' 或 'drop-newest' 的写入者来说,这会等待物理容量,即使写入不会阻塞。这允许生产者在写入前等待,从而避免数据丢失。
🌐 For writers using 'drop-oldest' or 'drop-newest', this waits for physical
capacity even though writes do not block. This allows producers to avoid data
loss by waiting before writing.
import { push, ondrain, text } from 'node:stream/iter';
const { writer, readable } = push({ budget: 16384 });
const chunk = new Uint8Array(8192); // 8 KB
writer.writeSync(chunk);
writer.writeSync(chunk); // 16 KB total -- buffer full
// Start consuming so the buffer can actually drain
const consuming = text(readable);
// Buffer is full -- wait for drain
const canWrite = await ondrain(writer);
if (canWrite) {
await writer.write('c');
}
await writer.end();
await consuming;const { push, ondrain, text } = require('node:stream/iter');
async function run() {
const { writer, readable } = push({ budget: 16384 });
const chunk = new Uint8Array(8192); // 8 KB
writer.writeSync(chunk);
writer.writeSync(chunk); // 16 KB total -- buffer full
// Start consuming so the buffer can actually drain
const consuming = text(readable);
// Buffer is full -- wait for drain
const canWrite = await ondrain(writer);
if (canWrite) {
await writer.write('c');
}
await writer.end();
await consuming;
}
run().catch(console.error);