> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Lines

> Answer head, tail and wc -l from a service's own queries.

Lines lets a VFS answer `head`, `tail`, `wc -l` and `tail -f` without reading
the whole file. [Built-in VFSs](https://docs.mirage.strukto.ai/home/integration/overview.md#lines) lists which
VFSs support it.

## VFS and Lines Integration

A VFS overrides the methods its service can answer. Each method returns
exactly what a read would hold, or `None` (TypeScript: `null`) when it cannot
answer, and Mirage reads the file instead. TypeScript names methods in
camelCase (`first_lines` is `firstLines`) and returns `Uint8Array` for
`bytes`. A command reading standard input never asks. The examples extend
`NotesVFS` from [Adding a New VFS](https://docs.mirage.strukto.ai/home/setup/vfs/new.md#write-one), mounted at
`/notes`.

### `first_lines`

The first lines of one file.

**Commands:** `head`, `head -n N` and `head -N`. `head -c N`, `head -n -N` and
`head -z` read the file without asking.

**path** `PathSpec` *required*

The file, on this mount.

**n** `int` *required*

How many lines to return, 1 or more.

**Examples:**

| Command | `path` | `n` |
| - | - | - |
| `head /notes/todo.txt` | `/notes/todo.txt` | `10` |
| `head -n 3 /notes/todo.txt` | `/notes/todo.txt` | `3` |

**returns** `bytes | None`

| Return | What happens |
| - | - |
| The first `n` lines, or the whole file if it is shorter | `head` prints them, and the file is not read. |
| `None` | The file is read. |

> [tab] Python
>
> ```python theme={null}
> import io
>
> from mirage import PathSpec
>
> from notes import NotesVFS
>
>
> class LinesNotesVFS(NotesVFS):
>     async def first_lines(self, path: PathSpec, n: int) -> bytes | None:
>         lines = io.StringIO(self.page(path), newline="\n").readlines()
>         return "".join(lines[:n]).encode()
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import type { PathSpec } from '@struktoai/mirage-node'
> import { NotesVFS } from './notes.ts'
>
> export class LinesNotesVFS extends NotesVFS {
>   override async firstLines(path: PathSpec, n: number): Promise<Uint8Array | null> {
>     const lines = this.page(path).split(/(?<=\n)/)
>     return new TextEncoder().encode(lines.slice(0, n).join(''))
>   }
> }
> ```

With this example, `head -n 1` on a page reads nothing, and `head -c 3` still
reads it.

### `last_lines`

The last lines of one file.

**Commands:** `tail`, `tail -n N` and `tail -N`. `tail -c N` and `tail -n +N`
read the file without asking.

**path** `PathSpec` *required*

The file, on this mount.

**n** `int` *required*

How many lines to return, 1 or more.

**Examples:**

| Command | `path` | `n` |
| - | - | - |
| `tail /notes/todo.txt` | `/notes/todo.txt` | `10` |
| `tail -n 5 /notes/todo.txt` | `/notes/todo.txt` | `5` |

**returns** `bytes | None`

| Return | What happens |
| - | - |
| The last `n` lines, or the whole file if it is shorter | `tail` prints them, and the file is not read. |
| `None` | The file is read. |

> [tab] Python
>
> ```python theme={null}
> import io
>
> from mirage import PathSpec
>
> from notes import NotesVFS
>
>
> class LinesNotesVFS(NotesVFS):
>     async def last_lines(self, path: PathSpec, n: int) -> bytes | None:
>         lines = io.StringIO(self.page(path), newline="\n").readlines()
>         return "".join(lines[max(len(lines) - n, 0) :]).encode()
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import type { PathSpec } from '@struktoai/mirage-node'
> import { NotesVFS } from './notes.ts'
>
> export class LinesNotesVFS extends NotesVFS {
>   override async lastLines(path: PathSpec, n: number): Promise<Uint8Array | null> {
>     const lines = this.page(path).split(/(?<=\n)/)
>     return new TextEncoder().encode(lines.slice(Math.max(lines.length - n, 0)).join(''))
>   }
> }
> ```

### `line_count`

The number of lines in one file.

**Commands:** `wc -l`. `wc` with another count (`-c`, `-w`, `-m` or `-L`)
reads the file without asking.

**path** `PathSpec` *required*

The file, on this mount.

**Examples:**

| Command | `path` |
| - | - |
| `wc -l /notes/todo.txt` | `/notes/todo.txt` |

**returns** `int | None`

| Return | What happens |
| - | - |
| The number of newline characters in the file | `wc -l` prints it, and the file is not read. |
| `None` | The file is read. |

> [tab] Python
>
> ```python theme={null}
> from mirage import PathSpec
>
> from notes import NotesVFS
>
>
> class LinesNotesVFS(NotesVFS):
>     async def line_count(self, path: PathSpec) -> int | None:
>         return self.page(path).count("\n")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import type { PathSpec } from '@struktoai/mirage-node'
> import { NotesVFS } from './notes.ts'
>
> export class LinesNotesVFS extends NotesVFS {
>   override async lineCount(path: PathSpec): Promise<number | null> {
>     return this.page(path).split('\n').length - 1
>   }
> }
> ```

### `follow`

The last lines of one file, then each new line as it arrives.

**Commands:** `tail -f` and `tail -f -n N` on one file. `tail -F`,
`tail --follow=name`, `tail -f -c N`, `tail -f -n +N` and `tail -f` on more
than one file read the file every `interval` seconds without asking.

**path** `PathSpec` *required*

The file, on this mount.

**n** `int` *required*

How many of the file's last lines to send first, 0 for none.

**interval** `float` *required*

The seconds between two checks for new lines. A service that pushes new lines can ignore it.

**Examples:**

| Command | `path` | `n` | `interval` |
| - | - | - | - |
| `tail -f /notes/log.txt` | `/notes/log.txt` | `10` | `1.0` |
| `tail -f -n 0 -s 5 /notes/log.txt` | `/notes/log.txt` | `0` | `5.0` |

**returns** `AsyncIterator[bytes] | None`

| Return | What happens |
| - | - |
| A stream that yields the last `n` lines, then each new whole line in order, and never ends on its own | `tail -f` prints it until it is stopped. If the stream ends, `tail -f` exits 1 with `tail: no files remaining`. |
| `None` | The file is read every `interval` seconds. |

> [tab] Python
>
> ```python theme={null}
> import asyncio
> import io
> from collections.abc import AsyncIterator
>
> from mirage import PathSpec
>
> from notes import NotesVFS
>
>
> class FollowNotesVFS(NotesVFS):
>     async def follow(
>         self, path: PathSpec, n: int, interval: float
>     ) -> AsyncIterator[bytes] | None:
>         async def lines() -> AsyncIterator[bytes]:
>             seen = self.page(path)
>             old = io.StringIO(seen, newline="\n").readlines()
>             yield "".join(old[max(len(old) - n, 0) :]).encode()
>             while True:
>                 await asyncio.sleep(interval)
>                 page = self.page(path)
>                 if len(page) < len(seen):
>                     seen = ""
>                 yield page[len(seen) :].encode()
>                 seen = page
>
>         return lines()
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import type { PathSpec } from '@struktoai/mirage-node'
> import { NotesVFS } from './notes.ts'
>
> export class FollowNotesVFS extends NotesVFS {
>   override async follow(
>     path: PathSpec,
>     n: number,
>     interval: number,
>   ): Promise<AsyncIterable<Uint8Array> | null> {
>     const page = (): string => this.page(path)
>     async function* lines(): AsyncGenerator<Uint8Array> {
>       let seen = page()
>       const old = seen.split(/(?<=\n)/)
>       yield new TextEncoder().encode(old.slice(Math.max(old.length - n, 0)).join(''))
>       for (;;) {
>         await new Promise((resolve) => setTimeout(resolve, interval * 1000))
>         const now = page()
>         if (now.length < seen.length) seen = ''
>         yield new TextEncoder().encode(now.slice(seen.length))
>         seen = now
>       }
>     }
>     return lines()
>   }
> }
> ```

A real service would push new lines over a stream. This example checks the
dictionary every `interval` seconds instead. It yields on every check, an
empty chunk when nothing is new, so a stopped `tail -f` closes it within one
interval. It starts over when the page shrinks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.