Skip to content

Commit 4bf3d44

Browse files
mertcanaltinmarco-ippolito
authored andcommittedJun 17, 2024
doc: update fs read documentation for clarity
PR-URL: #52453 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent ae5d47d commit 4bf3d44

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
 

‎doc/api/fs.md

+31
Original file line numberDiff line numberDiff line change
@@ -3555,6 +3555,37 @@ number of bytes read is zero.
35553555
If this method is invoked as its [`util.promisify()`][]ed version, it returns
35563556
a promise for an `Object` with `bytesRead` and `buffer` properties.
35573557
3558+
The `fs.read()` method reads data from the file specified
3559+
by the file descriptor (`fd`).
3560+
The `length` argument indicates the maximum number
3561+
of bytes that Node.js
3562+
will attempt to read from the kernel.
3563+
However, the actual number of bytes read (`bytesRead`) can be lower
3564+
than the specified `length` for various reasons.
3565+
3566+
For example:
3567+
3568+
* If the file is shorter than the specified `length`, `bytesRead`
3569+
will be set to the actual number of bytes read.
3570+
* If the file encounters EOF (End of File) before the buffer could
3571+
be filled, Node.js will read all available bytes until EOF is encountered,
3572+
and the `bytesRead` parameter in the callback will indicate
3573+
the actual number of bytes read, which may be less than the specified `length`.
3574+
* If the file is on a slow network `filesystem`
3575+
or encounters any other issue during reading,
3576+
`bytesRead` can be lower than the specified `length`.
3577+
3578+
Therefore, when using `fs.read()`, it's important to
3579+
check the `bytesRead` value to
3580+
determine how many bytes were actually read from the file.
3581+
Depending on your application
3582+
logic, you may need to handle cases where `bytesRead`
3583+
is lower than the specified `length`,
3584+
such as by wrapping the read call in a loop if you require
3585+
a minimum amount of bytes.
3586+
3587+
This behavior is similar to the POSIX `preadv2` function.
3588+
35583589
### `fs.read(fd[, options], callback)`
35593590
35603591
<!-- YAML

0 commit comments

Comments
 (0)
Please sign in to comment.