From a27f473c263328cecc55da9d0778b21d395766d5 Mon Sep 17 00:00:00 2001 From: Mert Can Altin Date: Fri, 10 May 2024 21:04:05 +0300 Subject: [PATCH] doc: update fs read documentation for clarity PR-URL: https://github.com/nodejs/node/pull/52453 Reviewed-By: Matteo Collina Reviewed-By: Marco Ippolito Reviewed-By: James M Snell --- doc/api/fs.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/doc/api/fs.md b/doc/api/fs.md index 3c7437bbd4f090..a701af6123793e 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -3681,6 +3681,37 @@ number of bytes read is zero. If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffer` properties. +The `fs.read()` method reads data from the file specified +by the file descriptor (`fd`). +The `length` argument indicates the maximum number +of bytes that Node.js +will attempt to read from the kernel. +However, the actual number of bytes read (`bytesRead`) can be lower +than the specified `length` for various reasons. + +For example: + +* If the file is shorter than the specified `length`, `bytesRead` + will be set to the actual number of bytes read. +* If the file encounters EOF (End of File) before the buffer could + be filled, Node.js will read all available bytes until EOF is encountered, + and the `bytesRead` parameter in the callback will indicate + the actual number of bytes read, which may be less than the specified `length`. +* If the file is on a slow network `filesystem` + or encounters any other issue during reading, + `bytesRead` can be lower than the specified `length`. + +Therefore, when using `fs.read()`, it's important to +check the `bytesRead` value to +determine how many bytes were actually read from the file. +Depending on your application +logic, you may need to handle cases where `bytesRead` +is lower than the specified `length`, +such as by wrapping the read call in a loop if you require +a minimum amount of bytes. + +This behavior is similar to the POSIX `preadv2` function. + ### `fs.read(fd[, options], callback)`