filehandle.readFile(options)
options<Object> | <string>encoding<string> | <null> 默认:nullsignal<AbortSignal> 允许中止正在进行的 readFile 操作buffer<Buffer> | <TypedArray> | <DataView> | <Function> 一个用于读取的缓冲区,或者一个以文件大小为参数返回缓冲区的函数。
- 返回:<Promise> 在成功读取文件内容后完成。如果未指定编码(使用
options.encoding),数据将作为 <Buffer> 对象返回。否则,数据将是一个字符串。
异步地读取文件的全部内容。
🌐 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();
}