> ## 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 your service.

`head`, `tail`, `wc -l` and `tail -f` can ask your VFS for lines or a count,
instead of reading the file. Return exactly what a read would hold, or `None`
(TypeScript: `null`) and Mirage reads the file.

For example, [PostgreSQL](https://docs.mirage.strukto.ai/python/vfs/postgres.md) answers
`head -n 20 rows.jsonl` with `LIMIT 20` and `wc -l rows.jsonl` with
`COUNT(*)`.

## `first_lines`

The first lines of one file.

> [tab] Python
>
> ```python theme={null}
> async def first_lines(self, path: PathSpec, n: int) -> bytes | None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> firstLines(path: PathSpec, n: number): Promise<Uint8Array | null>
> ```

| Argument | Meaning |
| - | - |
| `path` | The file. |
| `n` | How many lines, 1 or more. |

| Return | Mirage then |
| - | - |
| The first `n` lines, or all of them if the file is shorter | Prints them. The file is not read. |
| `None` | Reads the file. |

These commands call `first_lines`:

* `head`: the first 10 lines
* `head -n N`, `head -N`: the first N lines

These read the file instead:

* `head -c N`: the first N bytes
* `head -n -N`: all but the last N lines
* `head -z`: lines end with NUL
* standard input

## `last_lines`

The last lines of one file.

> [tab] Python
>
> ```python theme={null}
> async def last_lines(self, path: PathSpec, n: int) -> bytes | None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> lastLines(path: PathSpec, n: number): Promise<Uint8Array | null>
> ```

| Argument | Meaning |
| - | - |
| `path` | The file. |
| `n` | How many lines, 1 or more. |

| Return | Mirage then |
| - | - |
| The last `n` lines, or all of them if the file is shorter | Prints them. The file is not read. |
| `None` | Reads the file. |

These commands call `last_lines`:

* `tail`: the last 10 lines
* `tail -n N`, `tail -N`: the last N lines

These read the file instead:

* `tail -c N`: the last N bytes
* `tail -n +N`: from line N on
* standard input

## `line_count`

The number of lines in one file.

> [tab] Python
>
> ```python theme={null}
> async def line_count(self, path: PathSpec) -> int | None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> lineCount(path: PathSpec): Promise<number | null>
> ```

| Argument | Meaning |
| - | - |
| `path` | The file. |

| Return | Mirage then |
| - | - |
| The number of newline characters | Prints it. The file is not read. |
| `None` | Reads the file. |

This command calls `line_count`:

* `wc -l`

These read the file instead:

* `wc` with another count: `-c`, `-w`, `-m` or `-L`
* standard input

## Example: head, tail and wc -l

This example extends `NotesVFS` from [Custom VFS](https://docs.mirage.strukto.ai/home/setup/custom-vfs.md#example-a-read-only-vfs):

> [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()
>
>     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()
>
>     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 firstLines(path: PathSpec, n: number): Promise<Uint8Array | null> {
>     const lines = this.page(path).split(/(?<=\n)/)
>     return new TextEncoder().encode(lines.slice(0, n).join(''))
>   }
>
>   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(''))
>   }
>
>   override async lineCount(path: PathSpec): Promise<number | null> {
>     return this.page(path).split('\n').length - 1
>   }
> }
> ```

`head -n 1`, `tail -n 1` and `wc -l` on a page then read nothing. `head -c 3`
still reads it.

## `follow`

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

> [tab] Python
>
> ```python theme={null}
> async def follow(
>     self, path: PathSpec, n: int, interval: float
> ) -> AsyncIterator[bytes] | None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> follow(
>   path: PathSpec,
>   n: number,
>   interval: number,
> ): Promise<AsyncIterable<Uint8Array> | null>
> ```

| Argument | Meaning |
| - | - |
| `path` | The file. |
| `n` | How many of its last lines come first, 0 for none. |
| `interval` | Seconds between two checks for new lines (`tail -s`, 1 by default). A service that pushes new lines can ignore it. |

| Return | Mirage then |
| - | - |
| A stream that yields the last `n` lines, then each new whole line in order, and never ends on its own | Prints it until the caller stops `tail -f`. If the stream ends, `tail -f` exits 1 with `tail: no files remaining`. |
| `None` | Reads the file every `interval` seconds. |

These commands call `follow`:

* `tail -f`, `tail -f -n N` on one file

These read the file every `interval` seconds instead:

* `tail -F`, `tail --follow=name`: follow the name, not the file
* `tail -f -c N`
* `tail -f -n +N`
* `tail -f` on more than one file

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

> [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()
>   }
> }
> ```


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