当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。