filehandle.readFile(options)


异步地读取文件的全部内容。

🌐 Asynchronously reads the entire contents of a file.

如果 options 是一个字符串,那么它指定了 encoding

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

如果提供了 buffer 且没有指定编码,返回的 <Buffer> 是对所提供缓冲区的一个视图,只包含已读取的字节。如果提供的缓冲区太小而无法容纳整个文件,操作将会失败。

🌐 If buffer is provided and no encoding is specified, the returned <Buffer> is a view over the supplied buffer containing only the bytes read. If the supplied buffer is too small to contain the entire file, the operation will fail.

<FileHandle> 必须支持读取。

🌐 The <FileHandle> has to support reading.

如果对一个文件句柄调用一次或多次 filehandle.read(),然后再调用 filehandle.readFile(),数据将从当前位置读取到文件末尾。它并不总是从文件开头开始读取。

🌐 If one or more filehandle.read() calls are made on a file handle and then a filehandle.readFile() call is made, the data will be read from the current position till the end of the file. It doesn't always read from the beginning of the file.

使用预分配缓冲区和 buffer 选项的示例:

🌐 An example using the buffer option with a pre-allocated buffer:

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

const file = await open('./some/file/to/read');
try {
  const buf = Buffer.alloc(16384);
  const contents = await file.readFile({ buffer: buf });
  console.log(contents); // A view over `buf` containing only the bytes read
} finally {
  await file.close();
} 

使用 buffer 选项和返回缓冲区的函数的示例:

🌐 An example using the buffer option with a function returning a buffer:

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

const file = await open('./some/file/to/read');
try {
  const contents = await file.readFile({
    buffer: (size) => Buffer.alloc(size),
  });
  console.log(contents);
} finally {
  await file.close();
}