Skip to content

fix: support string encoding parameter in readFile#17

Merged
CoderSerio merged 1 commit intomainfrom
fix/readfile-encoding-param
Mar 2, 2026
Merged

fix: support string encoding parameter in readFile#17
CoderSerio merged 1 commit intomainfrom
fix/readfile-encoding-param

Conversation

@CoderSerio
Copy link
Owner

@CoderSerio CoderSerio commented Mar 1, 2026

🌌 Fix for Issue #16

Problem

readFile(path, "utf-8") was ignoring the string encoding parameter and always returning Buffer, inconsistent with Node.js native fs.readFile() behavior.

Root Cause

The Rust function signature only accepted Option<ReadFileOptions> (object form), so when a string was passed:

  • readFile("file.txt", "utf-8")options.encoding was undefined → returned Buffer
  • readFile("file.txt", { encoding: "utf-8" }) → worked correctly ✅

Solution

Use NAPI-RS Either<String, ReadFileOptions> to accept both parameter forms:

fn normalize_read_file_options(
  options: Option<Either<String, ReadFileOptions>>,
) -> ReadFileOptions {
  match options {
    Some(Either::A(encoding)) => ReadFileOptions {
      encoding: Some(encoding),  // String → encoding
      flag: None,
    },
    Some(Either::B(opts)) => opts,  // Object → as-is
    None => ReadFileOptions {
      encoding: None,
      flag: None,
    },
  }
}

Changes

  • src/read_file.rs: Updated function signatures and added normalization helper
  • test/read_file.spec.ts: Added 3 test cases covering:
    • readFile(path, "utf-8") → returns String ✅
    • readFile(path, { encoding: "utf-8" }) → returns String ✅
    • readFile(path) → returns Buffer ✅

Testing

All new tests pass. The API is now fully consistent with Node.js native fs.readFile().

Closes #16

Summary by CodeRabbit

  • Tests

    • Added test coverage for file reading operations with various encoding parameter formats, including string encoding and options object variations.
  • New Features

    • File reading API now accepts encoding parameters in multiple formats for improved flexibility—either as a direct string or as part of an options object.

- Add Either<String, ReadFileOptions> to accept both string and object forms
- Add normalize_read_file_options helper for parameter normalization
- Add tests for string encoding, object encoding, and no encoding cases
- Fixes issue #16 where readFile(path, "utf-8") incorrectly returned Buffer
@vercel
Copy link

vercel bot commented Mar 1, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rush-fs-docs Building Building Preview, Comment Mar 1, 2026 7:16pm

@coderabbitai
Copy link

coderabbitai bot commented Mar 1, 2026

📝 Walkthrough

Walkthrough

The PR refactors readFile option handling to accept either string encoding or full options objects via an Either type, introduces a normalization helper function, and adds tests verifying correct return types (string with encoding, Buffer without).

Changes

Cohort / File(s) Summary
Test Coverage
__test__/read_file.spec.ts
Added three new tests validating readFile return types: string when encoding is provided (both string and object forms), Buffer when no encoding is specified.
Read File Implementation
src/read_file.rs
Refactored option handling to accept Option<Either<String, ReadFileOptions>> across public and internal functions. Introduced normalize_read_file_options helper to unify string encoding and object options into normalized ReadFileOptions. Updated signatures for read_file, read_file_sync, read_file_impl, and ReadFileTask struct.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 ✨ With Either paths we now can take,
String or struct—whichever makes sense to make!
Options normalize, buffers transform to text,
Node.js-like behavior—what comes next?
A little hopper's heart sings true! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding support for string encoding parameters in readFile, which is the core fix addressing Issue #16.
Linked Issues check ✅ Passed The PR fully implements the objectives from Issue #16: readFile now accepts Either<String, ReadFileOptions>, normalizes string encoding to ReadFileOptions, and tests verify that string encoding returns string and no encoding returns Buffer.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing Issue #16: Rust binding modifications to accept Either type, normalization helper, and test cases for encoding parameter support.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/readfile-encoding-param

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/read_file.rs (1)

155-161: Consider adding test coverage for readFileSync with string encoding.

The sync function also supports the new string encoding parameter, but there's no test verifying readFileSync('./package.json', 'utf-8') returns a string. The existing tests only use the object form.

💡 Suggested test to add in __test__/read_file.spec.ts
test('readFileSync: should read file as string with encoding as string param', (t) => {
  const result = readFileSync('./package.json', 'utf-8')
  t.is(typeof result, 'string')
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/read_file.rs` around lines 155 - 161, Add a unit test to cover the
string-encoding variant of the synchronous API: create a test in
__test__/read_file.spec.ts that calls readFileSync('./package.json', 'utf-8')
and asserts the result is a string (e.g. typeof result === 'string'); this
ensures read_file_sync (which forwards to read_file_impl) correctly returns a
string when a plain string encoding is passed instead of the object form.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/read_file.rs`:
- Around line 155-161: Add a unit test to cover the string-encoding variant of
the synchronous API: create a test in __test__/read_file.spec.ts that calls
readFileSync('./package.json', 'utf-8') and asserts the result is a string (e.g.
typeof result === 'string'); this ensures read_file_sync (which forwards to
read_file_impl) correctly returns a string when a plain string encoding is
passed instead of the object form.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2681195 and 0545c8f.

📒 Files selected for processing (2)
  • __test__/read_file.spec.ts
  • src/read_file.rs

@CoderSerio CoderSerio merged commit dbf95d4 into main Mar 2, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

readFile() ignores encoding parameter and always returns Buffer

1 participant