method

fs.promises.FileHandle.readFile

readFile<T extends ArrayBufferView<ArrayBufferLike>>(
options: Omit<ReadFileOptionsWithBuffer<T>, 'flag'>
): Promise<BufferView<T>>;

Asynchronously reads the entire contents of a file.

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

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.

The FileHandle has to support reading.

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.

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();
}

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();
}
@returns

Fulfills upon a successful read with the contents of the file. If no encoding is specified (using options.encoding), the data is returned as a Buffer object. Otherwise, the data will be a string.

options?: null | Omit<ReadFileOptionsWithBufferEncoding, 'flag'>
): Promise<NonSharedBuffer>;
options: BufferEncoding | Omit<ReadFileOptionsWithStringEncoding, 'flag'>
): Promise<string>;
options: null | BufferEncoding | Omit<ReadFileOptions, 'flag'>
): Promise<string | NonSharedBuffer>;

Referenced types

interface ReadFileOptionsWithBuffer<T extends NodeJS.ArrayBufferView>

interface ReadFileOptions