filehandle.createReadStream([options])


options 可以包含 startend 值,用于读取以下范围内的字节是文件而不是整个文件。startend 都是包容性的, 从0开始计数,允许的值在 [0, Number.MAX_SAFE_INTEGER] 范围。如果 start 是 省略或 undefinedfs.createReadStream() 顺序读取于 当前文件位置。encoding 可以是以下任何一种被接受的 <Buffer>

如果 FileHandle 指向一个只支持阻塞读取的字符设备(例如键盘或声卡),读取操作将不会完成,直到有数据可用。这可能会阻止进程退出并使流无法自然关闭。

【If the FileHandle points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.】

默认情况下,流在被销毁后会触发 'close' 事件。将 emitClose 选项设置为 false 可以更改此行为。

【By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.】

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 为 false,即使发生错误,文件描述符也不会关闭。由应用负责关闭文件描述符,并确保没有文件描述符泄漏。如果 autoClose 设置为 true(默认行为),在 'error''end' 时文件描述符将会自动关闭。

【If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.】

读取 100 个字节长的文件的最后 10 个字节的示例:

【An example to read the last 10 bytes of a file which is 100 bytes long:】

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

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