denoland / denoland/std

Add Utility Function to Ensure Exact Number of Bytes Read from File

Open
#5,929 2 comments 0 reactions 0 assignees View on GitHub
feedback welcome
Dominant language
TypeScript
Stars
3.6k
Forks
681
PR merge metrics
No merged PRs in 30d

Description

**Is your feature request related to a problem? Please describe.**

Currently, Deno provides `Deno.readFile()`, which reads an entire file into a buffer, and `Deno.FsFile.read()`, which reads a portion of a file into a buffer. However, `Deno.FsFile.read()` may return before reading the full requested number of bytes. This creates a challenge when attempting to reliably read *exactly* a specified number of bytes, requiring users to write custom logic to ensure they handle partial reads correctly.

**Describe the solution you'd like**

I propose adding a utility function to the standard library that abstracts away the complexity of handling partial reads, ensuring that the desired number of bytes is read into a buffer. This function might behave similarly to the following code:

```typescript
export async function read(file: Deno.FsFile, buffer: Uint8Array): Promise {
let offset = 0
while (offset < buffer.byteLength) {
const bytesRead = await file.read(buffer.subarray(offset))
if (bytesRead == null) break
offset += bytesRead
}
return buffer.subarray(0, offset)
}
```

This function would ensure that the buffer is filled (if possible) or gracefully handle end-of-file conditions without requiring developers to write custom loops.

**Describe alternatives you've considered**

Alternatives include manually implementing this logic in every project, as illustrated above. However, this approach leads to code duplication and potential bugs across codebases.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.