readable.read([size])
參數
readable.read() 方法從內部緩衝區中讀取數據並返回。如果沒有數據可供讀取,則返回null。默認情況下,除非使用 readable.setEncoding() 方法指定了編碼或流在對象模式下運行,否則數據將作為 Buffer 對象返回。
可選的size 參數指定要讀取的特定字節數。如果 size 字節不可讀取,則將返回 null,除非流已結束,在這種情況下,將返回內部緩衝區中剩餘的所有數據。
如果未指定size 參數,則將返回內部緩衝區中包含的所有數據。
size 參數必須小於或等於 1 GiB。
readable.read() 方法隻能在以暫停模式運行的Readable 流上調用。在流動模式下,會自動調用readable.read(),直到內部緩衝區完全耗盡。
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
每次調用 readable.read() 都會返回一個數據塊,或 null 。塊沒有連接。 while 循環是消耗當前在緩衝區中的所有數據所必需的。讀取大文件時 .read() 可能會返回 null ,到目前為止已經消耗了所有緩衝的內容,但仍有更多數據尚未緩衝。在這種情況下,當緩衝區中有更多數據時,將發出一個新的 'readable' 事件。最後,當沒有更多數據到來時,將發出 'end' 事件。
因此,要從 readable 讀取文件的全部內容,有必要跨多個 'readable' 事件收集塊:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
無論 size 參數的值如何,對象模式下的 Readable 流將始終從對 的調用返回單個項目。readable.read(size)
如果readable.read() 方法返回一個數據塊,也會發出一個'data' 事件。
在發出 事件後調用 'end' 將返回 stream.read([size]) null 。不會引發運行時錯誤。
相關用法
- Node.js stream.Readable.resume()用法及代碼示例
- Node.js stream.Readable.reduce(fn[, initial[, options]])用法及代碼示例
- Node.js stream.Readable.take(limit[, options])用法及代碼示例
- Node.js stream.Readable.pipe(destination[, options])用法及代碼示例
- Node.js stream.Readable.setEncoding(encoding)用法及代碼示例
- Node.js stream.Readable.some(fn[, options])用法及代碼示例
- Node.js stream.Readable.map(fn[, options])用法及代碼示例
- Node.js stream.Readable.toArray([options])用法及代碼示例
- Node.js stream.Readable.isPaused()用法及代碼示例
- Node.js stream.Readable.forEach(fn[, options])用法及代碼示例
- Node.js stream.Readable.every(fn[, options])用法及代碼示例
- Node.js stream.Readable.from()用法及代碼示例
- Node.js stream.Readable.flatMap(fn[, options])用法及代碼示例
- Node.js stream.Readable.unshift(chunk[, encoding])用法及代碼示例
- Node.js stream.Readable.filter(fn[, options])用法及代碼示例
- Node.js stream.Readable.asIndexedPairs([options])用法及代碼示例
- Node.js stream.Readable.drop(limit[, options])用法及代碼示例
- Node.js stream.Readable.iterator([options])用法及代碼示例
- Node.js stream.Readable.wrap(stream)用法及代碼示例
- Node.js stream.Readable.find(fn[, options])用法及代碼示例
- Node.js stream.Readable.unpipe([destination])用法及代碼示例
- Node.js stream.Readable.pause()用法及代碼示例
- Node.js stream.Readable.from(iterable[, options])用法及代碼示例
- Node.js stream.Writable.uncork()用法及代碼示例
- Node.js stream.finished()用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 stream.Readable.read([size])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
