fs.createReadStream(path[, options])


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

如果指定了 fdReadStream 将忽略 path 参数,并使用指定的文件描述符。这意味着不会触发 'open' 事件。fd 应该是阻塞的;非阻塞的 fd 应该传递给 <net.Socket>

【If fd is specified, ReadStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to <net.Socket>.】

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

【If fd 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.】

通过提供 fs 选项,可以覆盖 openreadclose 的对应 fs 实现。当提供 fs 选项时,必须提供 read 的覆盖实现。如果未提供 fd,还需要提供 open 的覆盖实现。如果 autoClosetrue,还需要提供 close 的覆盖实现。

【By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option, an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is also required.】

import { createReadStream } from 'node:fs';

// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
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.】

mode 设置文件模式(权限和粘滞位),但仅在文件被创建时生效。

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

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

import { createReadStream } from 'node:fs';

createReadStream('sample.txt', { start: 90, end: 99 }); 

如果 options 是字符串,那么它指定了编码。

【If options is a string, then it specifies the encoding.】