fsPromises.readFile(path[, options])
path<string> | <Buffer> | <URL> | <FileHandle> 文件名或FileHandleoptions<Object> | <string>encoding<string> | <null> 默认值:nullflag<string> 请参阅对文件系统flags的支持。 默认值:'r'。signal<AbortSignal> 允许中止正在进行的读取文件
- 返回: <Promise> 使用文件的内容履行。
异步地读取文件的全部内容。
如果未指定编码(使用 options.encoding),则数据作为 <Buffer> 对象返回。
否则,数据将为字符串。
如果 options 是字符串,则它指定编码。
当 path 是目录时,fsPromises.readFile() 的行为是特定于平台的。
在 macOS、Linux 和 Windows 上,promise 将使用错误拒绝。
在 FreeBSD 上,将返回目录内容的表示。
可以使用 <AbortSignal> 中止正在进行的 readFile。
如果请求中止,则返回的 promise 将使用 AbortError 拒绝:
import { readFile } from 'fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// 在 promise 达成之前中止请求。
controller.abort();
await promise;
} catch (err) {
// 当请求中止时 - err 是 AbortError
console.error(err);
}中止正在进行的请求不会中止单个操作系统请求,而是中止内部缓冲的 fs.readFile 执行。
任何指定的 <FileHandle> 必须支持读取。
path<string> | <Buffer> | <URL> | <FileHandle> filename orFileHandleoptions<Object> | <string>encoding<string> | <null> Default:nullflag<string> See support of file systemflags. Default:'r'.signal<AbortSignal> allows aborting an in-progress readFile
- Returns: <Promise> Fulfills with the contents of the file.
Asynchronously reads the entire contents of a file.
If no encoding is specified (using options.encoding), the data is returned
as a <Buffer> object. Otherwise, the data will be a string.
If options is a string, then it specifies the encoding.
When the path is a directory, the behavior of fsPromises.readFile() is
platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.
It is possible to abort an ongoing readFile using an <AbortSignal>. If a
request is aborted the promise returned is rejected with an AbortError:
import { readFile } from 'fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering fs.readFile performs.
Any specified <FileHandle> has to support reading.