當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js FileHandle.createReadStream([options])用法及代碼示例

filehandle.createReadStream([options])

添加於:v16.11.0

參數

<stream.Readable> 的 16 KiB 默認 highWaterMark 不同,此方法返回的流的默認 highWaterMark 為 64 KiB。

options 可以包含 startend 值,以從文件而不是整個文件中讀取字節範圍。 startend 都包含在內並從 0 開始計數,允許的值在 [0, Number.MAX_SAFE_INTEGER ] 範圍內。如果省略 startundefined ,則 filehandle.createReadStream() 從當前文件位置開始順序讀取。 encoding 可以是 <Buffer> 接受的任何一種。

如果FileHandle 指向僅支持阻塞讀取的字符設備(例如鍵盤或聲卡),則讀取操作在數據可用之前不會完成。這可以防止進程退出和流自然關閉。

默認情況下,流將在銷毀後發出 'close' 事件。將 emitClose 選項設置為 false 以更改此行為。

import { open } from 'node:fs/promises';

const fd = await open('/dev/input/event0');
// Create a stream from some character device.
const stream = fd.createReadStream();
setTimeout(() => {
  stream.close(); // This may not close the stream.
  // Artificially marking end-of-stream, as if the underlying resource had
  // indicated end-of-file by itself, allows the stream to close.
  // This does not cancel pending read operations, and if there is such an
  // operation, the process may still not be able to exit successfully
  // until it finishes.
  stream.push(null);
  stream.read(0);
}, 100);

如果autoClose 為假,則即使出現錯誤,文件說明符也不會關閉。關閉它並確保沒有文件說明符泄漏是應用程序的責任。如果 autoClose 設置為 true(默認行為),則在 'error''end' 上,文件說明符將自動關閉。

讀取 100 字節長文件的最後 10 字節的示例:

import { open } from 'node:fs/promises';

const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 });

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 FileHandle.createReadStream([options])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。