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