readable.read([size])


从内部缓冲拉取并返回数据。 如果没有可读的数据,则返回 null。 默认情况下, readable.read() 返回的数据是 Buffer 对象,除非使用 readable.setEncoding() 指定字符编码或流处于对象模式。

如果可读的数据不足 size 个字节,则返回内部缓冲剩余的数据,如果流已经结束则返回 null

如果没有指定 size 参数,则返回内部缓冲中的所有数据。

readable.read() 应该只对处于暂停模式的可读流调用。 在流动模式中, readable.read() 会自动调用直到内部缓冲的数据完全耗尽。

const readable = getReadableStreamSomehow();
readable.on('readable', () => {
  let chunk;
  while (null !== (chunk = readable.read())) {
    console.log(`接收到 ${chunk.length} 字节的数据`);
  }
});

如果 readable.read() 返回一个数据块,则 'data'事件也会触发。

'end' 事件触发后再调用 stream.read([size]) 会返回null,不会抛出错误。

The readable.read() method pulls some data out of the internal buffer and returns it. If no data available to be read, null is returned. By default, the data will be returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

The optional size argument specifies a specific number of bytes to read. If size bytes are not available to be read, null will be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.

If the size argument is not specified, all of the data contained in the internal buffer will be returned.

The readable.read() method should only be called on Readable streams operating in paused mode. In flowing mode, readable.read() is called automatically until the internal buffer is fully drained.

const readable = getReadableStreamSomehow();
readable.on('readable', () => {
  let chunk;
  while (null !== (chunk = readable.read())) {
    console.log(`Received ${chunk.length} bytes of data.`);
  }
});

Note that the while loop is necessary when processing data with readable.read(). Only after readable.read() returns null, 'readable' will be emitted.

A Readable stream in object mode will always return a single item from a call to readable.read(size), regardless of the value of the size argument.

If the readable.read() method returns a chunk of data, a 'data' event will also be emitted.

Calling stream.read([size]) after the 'end' event has been emitted will return null. No runtime error will be raised.