( path: string, offset: number, maxBytes: number, )
| 642 | * larger parent. Returns null if the file is smaller than the offset. |
| 643 | */ |
| 644 | export async function readFileRange( |
| 645 | path: string, |
| 646 | offset: number, |
| 647 | maxBytes: number, |
| 648 | ): Promise<ReadFileRangeResult | null> { |
| 649 | await using fh = await open(path, 'r') |
| 650 | const size = (await fh.stat()).size |
| 651 | if (size <= offset) { |
| 652 | return null |
| 653 | } |
| 654 | const bytesToRead = Math.min(size - offset, maxBytes) |
| 655 | const buffer = Buffer.allocUnsafe(bytesToRead) |
| 656 | |
| 657 | let totalRead = 0 |
| 658 | while (totalRead < bytesToRead) { |
| 659 | const { bytesRead } = await fh.read( |
| 660 | buffer, |
| 661 | totalRead, |
| 662 | bytesToRead - totalRead, |
| 663 | offset + totalRead, |
| 664 | ) |
| 665 | if (bytesRead === 0) { |
| 666 | break |
| 667 | } |
| 668 | totalRead += bytesRead |
| 669 | } |
| 670 | |
| 671 | return { |
| 672 | content: buffer.toString('utf8', 0, totalRead), |
| 673 | bytesRead: totalRead, |
| 674 | bytesTotal: size, |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | /** |
| 679 | * Read the last `maxBytes` of a file. |
no test coverage detected