---
id: api/commands/readfile
title: cy.readFile()
description: >-
  Read files in Cypress tests with cy.readFile() to check downloads, logs, and
  generated files. It retries until the file exists and your assertions pass.
section: api
source_path: docs/api/commands/readfile.mdx
version: 1934fa485ad0afcbbd3bdb674d5c5f1f991b55cf
updated_at: '2026-11-14T05:15:51.878Z'
---
# readFile

`cy.readFile()` reads a file from disk and yields its contents. It reads the file again until the file exists and your assertions pass, so it suits files that change during a test, such as downloads, logs, and files your app generates. For test data that stays the same, use [`cy.fixture()`](/llm/markdown/api/commands/fixture.md), which reads the file once and caches it.

## Syntax

```
cy.readFile(filePath)
cy.readFile(filePath, encoding)
cy.readFile(filePath, options)
cy.readFile(filePath, encoding, options)
```

### Usage

**Correct Usage**

```
cy.readFile('menu.json')
```

### Arguments

**filePath _(String)_**

A path to a file, resolved relative to the project root (the directory that contains the [Cypress configuration file](/llm/markdown/app/references/configuration.md)). An absolute path also works.

**encoding _(String)_**

The encoding to use when reading the file. Defaults to `'utf8'`. The following encodings are supported:

*   `'ascii'`
*   `'base64'`
*   `'binary'`
*   `'hex'`
*   `'latin1'`
*   `'utf8'`
*   `'utf-8'`
*   `'ucs2'`
*   `'ucs-2'`
*   `'utf16le'`
*   `'utf-16le'`
*   `null`

Passing `null` yields the file as a [`Cypress.Buffer`](/llm/markdown/api/utilities/buffer.md) instance, regardless of file extension.

**options _(Object)_**

Pass in an options object to change the default behavior of `cy.readFile()`.

| Option | Default | Description |
| --- | --- | --- |
| `encoding` | `'utf8'` | The encoding to use when reading the file. Ignored when you pass `encoding` as the second argument instead. |
| `log` | `true` | Displays the command in the [Command Log](/llm/markdown/app/core-concepts/open-mode.md#Command-Log) |
| `timeout` | [`defaultCommandTimeout`](/llm/markdown/app/references/configuration.md#Timeouts) | Time to wait for `cy.readFile()` to resolve before [timing out](#Timeouts) |

### Yields

*   `cy.readFile()` yields the contents of the file. It parses a file with a `.json` extension into JavaScript, unless the encoding is `null`.
*   `cy.readFile()` reads the file from disk again if any upcoming command (such as an assertion) in the chain fails.

## Examples

### Text

#### Read a `.txt` file

For any file without a `.json` extension, `cy.readFile()` yields the contents of the file as a string.

path/to/message.txt

```
Hello World
```

spec.cy.js

```
cy.readFile('path/to/message.txt').should('eq', 'Hello World')
```

### JSON

For a file with a `.json` extension, `cy.readFile()` parses the contents into JavaScript and yields the result.

path/to/data.json

```
{
  "name": "Eliza",
  "email": "eliza@example.com"
}
```

spec.cy.js

```
cy.readFile('path/to/data.json').its('name').should('eq', 'Eliza')
```

#### Type a JSON file's contents in TypeScript

Pass a type argument to tell TypeScript the shape of the yielded contents.

*   JavaScript
*   TypeScript

spec.cy.js

```
cy.readFile('path/to/data.json').its('email').should('include', '@')
```

spec.cy.ts

```
type User = { name: string; email: string }

cy.readFile<User>('path/to/data.json').its('email').should('include', '@')
```

### YAML

#### Get translation data from a YAML file

`cy.readFile()` yields a YAML file as a string. Parse it with a YAML library, such as [`js-yaml`](https://www.npmjs.com/package/js-yaml).

languages/en.yml

```
sidebar:
  - Getting Started
  - API
```

spec.cy.js

```
const yaml = require('js-yaml')

cy.readFile('languages/en.yml').then((str) => {
  // parse the YAML string into an object
  const english = yaml.load(str)

  cy.get('#sidebar')
    .find('.sidebar-title')
    .each(($el, i) => {
      cy.wrap($el).should('have.text', english.sidebar[i])
    })
})
```

### Read files your app or server creates

#### Wait for a file download and check its contents

`cy.readFile()` retries until the file exists, so it waits for the downloaded file to appear. Build the path from the [`downloadsFolder`](/llm/markdown/app/references/configuration.md#Downloads) configuration.

```
cy.get('[data-cy="export-csv"]').click()
cy.readFile(`${Cypress.config('downloadsFolder')}/report.csv`).should(
  'contain',
  'Order ID'
)
```

#### Check a log file your server writes during a test

Read a file that your app or server writes as a side effect, such as a log. `cy.readFile()` reads the file again until the assertion passes.

```
// clicking "Save" makes the server append to logs/audit.log
cy.get('[data-cy="save-settings"]').click()
cy.readFile('logs/audit.log').should('contain', 'settings updated')
```

### Encoding

#### Specify the encoding with the second argument

```
cy.readFile('path/to/logo.png', 'base64').then((logo) => {
  // logo is encoded as base64
  // and looks something like this:
  // aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
})
```

#### Specify the encoding in the options object

Pass `encoding` alongside other options, such as a longer `timeout`.

```
cy.readFile('path/to/logo.png', { encoding: 'base64', timeout: 10000 }).should(
  'match',
  /^iVBOR/ // base64 for the PNG signature
)
```

#### Read a file as a Buffer with `null` encoding

```
cy.readFile('path/to/logo.png', null).then((logo) => {
  // logo is read as a buffer
  // and looks something like this:
  // Buffer([0, 0, ...])
})
```

#### Read a `.json` file as raw text without parsing it

To check the exact text of a `.json` file, such as its indentation, read it with `null` encoding and convert the Buffer to a string. `cy.readFile()` doesn't parse a file read this way.

```
cy.readFile('path/to/data.json', null).then((buf) => {
  expect(buf.toString()).to.include('"name": "Eliza"')
})
```

#### Play an MP3 file from its base64 contents

```
cy.readFile('audio/sound.mp3', 'base64').then((mp3) => {
  const uri = 'data:audio/mp3;base64,' + mp3
  const audio = new Audio(uri)

  audio.play()
})
```

### Reuse file contents in file uploads

#### Upload a file to an input with `.selectFile()`

Alias the contents of a file, then pass the alias to [`.selectFile()`](/llm/markdown/api/commands/selectfile.md). `cy.readFile()` stores the file name with the alias, so the upload keeps the original name.

```
cy.readFile('path/to/logo.png', null).as('logo')
cy.get('input[type=file]').selectFile('@logo')
```

## Notes

### Existence

#### Default file existence assertion

By default, `cy.readFile()` asserts that the file exists and fails if it does not. It retries reading the file until the file exists or the command times out.

```
// fails after the defaultCommandTimeout is reached
cy.readFile('does-not-exist.yaml')
```

The error shows the full path `cy.readFile()` resolved the file to, so you can check where Cypress looked for it.

`cy.readFile()` retries only when the file is missing. Any other error while reading, such as a `.json` file that contains invalid JSON, fails the command immediately.

#### Asserting file non-existence

Assert that a file does not exist with `.should('not.exist')`.

```
// passes if the file does not exist
cy.readFile('does-not-exist.yaml').should('not.exist')
```

#### Read a file that might not exist

To read a file that may not exist without failing the test, use [`cy.task()` to read a file that might not exist](/llm/markdown/api/commands/task.md#Read-a-file-that-might-not-exist-with-cytask) instead.

### Retries

#### Automatic retries

`cy.readFile()` reads the file again until it passes all of its assertions.

```
// if this assertion fails, cy.readFile() reads the file again
// until it passes its assertions (or times out)
cy.readFile('some/nested/path/story.txt').should('eq', 'Once upon a time...')
```

`cy.readFile()` is a [query](/llm/markdown/app/core-concepts/retry-ability.md#Only-queries-are-retried), so it reads the file again until all chained queries pass, not only assertions.

```
// retries until the JSON file has a `users[123].name` field and
// the assertion passes
cy.readFile('users.json').its('users.123.name').should('eq', 'John Doe')
```

### How `cy.readFile()` differs from `cy.fixture()`

This table compares the two commands. For when to reach for a static `import` or [`cy.task()`](/llm/markdown/api/commands/task.md) instead of either one, see [Choosing how to load test data in Cypress](/llm/markdown/app/core-concepts/writing-and-organizing-tests.md#Choosing-how-to-load-test-data-in-Cypress).

|  | `cy.fixture()` | `cy.readFile()` |
| --- | --- | --- |
| Path is relative to | `fixturesFolder` | The project root |
| File extension | Optional | Required |
| Reads from disk | Once per path and encoding, then yields the cached copy | On every call |
| Retries until assertions pass | No | Yes, reading the file again on each retry |
| Images by default | A `base64` string | A `utf8` string |
| Default timeout | `responseTimeout` | `defaultCommandTimeout` |
| Command Log | Not logged | Logged |
| Missing file | Always fails | Can be asserted with `.should('not.exist')` |

## Rules

### Requirements

*   `cy.readFile()` requires being chained off of `cy`.
*   `cy.readFile()` requires the file to exist, unless you assert that it does not with `.should('not.exist')`.
*   `cy.readFile()` requires the file be successfully read from disk.

### Assertions

*   `cy.readFile()` automatically [retries](/llm/markdown/app/core-concepts/retry-ability.md) until all chained assertions pass.

### Timeouts

*   `cy.readFile()` can time out waiting for assertions you've added to pass.
*   `cy.readFile()` can time out when reading the file takes longer than the `timeout`.

## Command Log

**_List the contents of your package.json file_**

```
cy.readFile('package.json')
```

The command above displays in the Command Log as:

Click the `readFile` command in the Command Log to see this in the console:

## History

| Version | Changes |
| --- | --- |
| [13.0.0](/llm/markdown/app/references/changelog.md#13-0-0) | `cy.readFile()` became a query |
| [9.0.0](/llm/markdown/app/references/changelog.md#9-0-0) | Changed `null` encoding to read as Buffer |
| [0.17.2](/llm/markdown/app/references/changelog.md#0-17-2) | Improved error messaging |
| [0.17.1](/llm/markdown/app/references/changelog.md#0-17-1) | `cy.readFile()` command added |

## See also

*   [`cy.fixture()`](/llm/markdown/api/commands/fixture.md) for a similar command with caching that does not retry
*   [`.selectFile()`](/llm/markdown/api/commands/selectfile.md) to upload a file you've read
*   [`cy.task()`](/llm/markdown/api/commands/task.md) to read a file that might not exist
*   [`cy.writeFile()`](/llm/markdown/api/commands/writefile.md)
