Skip to content

fs.ReadStream.bytesRead value meaning #5162

Description

@TeraV8

Node.js Version

v26.5.0

NPM Version

not installed

Operating System

Linux aarch64

Subsystem

fs

Description

Using a fs.ReadStream from fs.createReadStream() using no encoding:

fs.ReadStream.bytesRead appears (from my own testing) to reflect the total number of bytes read from the system, into the internal buffer, where I was erroneously using it to track the total number of bytes returned from read() calls. My code worked like this:

while (stream.bytesRead < endIndex) {
    const data = stream.read(Math.min(blockSize, endIndex - stream.bytesRead));
    if (data == null) {
        await sleep(50);
        continue;
    }
    // process data
}

The problem I was running into was that stream.bytesRead was only being updated during the sleep time, so when the stream reached endIndex while the script was waiting for data, the loop would exit early, and the last chunk would be skipped. I wrote the loop this way with the wrong assumption that bytesRead reflected the total number of bytes returned from read() calls, but I can understand that it represents bytes read from the system.

The API docs (https://nodejs.org/docs/latest/api/fs.html#readstreambytesread) don't provide much information about this, so can this be updated in the docs? Or did I make a mistake somewhere?

Minimal Reproduction

No response

Output

No response

Before You Submit

  • I have looked for issues that already exist before submitting this
  • My issue follows the guidelines in the README file, and follows the 'How to ask a good question' guide at https://stackoverflow.com/help/how-to-ask

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions