fsPromises.readFile(path[, options])


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

【Asynchronously reads the entire contents of a file.】

如果未指定编码(使用 options.encoding),数据将作为 <Buffer> 对象返回。否则,数据将是一个字符串。

【If no encoding is specified (using options.encoding), the data is returned as a <Buffer> object. Otherwise, the data will be a string.】

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

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

path 是一个目录时,fsPromises.readFile() 的行为取决于平台。在 macOS、Linux 和 Windows 上,Promise 会被拒绝并返回一个错误。在 FreeBSD 上,将返回该目录内容的表示。

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

在运行代码的同一目录中读取 package.json 文件的示例:

【An example of reading a package.json file located in the same directory of the running code:】

import { readFile } from 'node:fs/promises';
try {
  const filePath = new URL('./package.json', import.meta.url);
  const contents = await readFile(filePath, { encoding: 'utf8' });
  console.log(contents);
} catch (err) {
  console.error(err.message);
}const { readFile } = require('node:fs/promises');
const { resolve } = require('node:path');
async function logFile() {
  try {
    const filePath = resolve('./package.json');
    const contents = await readFile(filePath, { encoding: 'utf8' });
    console.log(contents);
  } catch (err) {
    console.error(err.message);
  }
}
logFile();

可以使用 <AbortSignal> 中止正在进行的 readFile。如果请求被中止,返回的 Promise 将以 AbortError 拒绝:

【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 'node: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);
} 

中止正在进行的请求并不会中止单个操作系统请求,而是中止内部缓冲 fs.readFile 所执行的操作。

【Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.】

任何指定的 <FileHandle> 都必须支持读取。

【Any specified <FileHandle> has to support reading.】