Skip to content

Commit 7d0f680

Browse files
committed
fs: use a default callback for fs.close()
The `fs.close()` function requires a callback. Most often the only thing that callback does is check and rethrow the error if one occurs. To eliminate common boilerplate, make the callback optional with a default that checks and rethrows the error as an uncaught exception. Signed-off-by: James M Snell <[email protected]> PR-URL: #37174 Reviewed-By: Juan José Arboleda <[email protected]> Reviewed-By: Antoine du Hamel <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Darshan Sen <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Zijian Liu <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent bf2f2b7 commit 7d0f680

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

doc/api/fs.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1618,10 +1618,13 @@ This is the synchronous version of [`fs.chown()`][].
16181618

16191619
See also: chown(2).
16201620

1621-
## `fs.close(fd, callback)`
1621+
## `fs.close(fd[, callback])`
16221622
<!-- YAML
16231623
added: v0.0.2
16241624
changes:
1625+
- version: REPLACEME
1626+
pr-url: https://github.com/nodejs/node/pull/37174
1627+
description: A default callback is now used if one is not provided.
16251628
- version: v10.0.0
16261629
pr-url: https://github.com/nodejs/node/pull/12562
16271630
description: The `callback` parameter is no longer optional. Not passing
@@ -1642,6 +1645,9 @@ to the completion callback.
16421645
Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
16431646
through any other `fs` operation may lead to undefined behavior.
16441647

1648+
If the `callback` argument is omitted, a default callback function that rethrows
1649+
any error as an uncaught exception will be used.
1650+
16451651
## `fs.closeSync(fd)`
16461652
<!-- YAML
16471653
added: v0.1.21

lib/fs.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -438,9 +438,14 @@ function readFileSync(path, options) {
438438
return buffer;
439439
}
440440

441-
function close(fd, callback) {
441+
function defaultCloseCallback(err) {
442+
if (err != null) throw err;
443+
}
444+
445+
function close(fd, callback = defaultCloseCallback) {
442446
validateInt32(fd, 'fd', 0);
443-
callback = makeCallback(callback);
447+
if (callback !== defaultCloseCallback)
448+
callback = makeCallback(callback);
444449

445450
const req = new FSReqCallback();
446451
req.oncomplete = callback;

0 commit comments

Comments
 (0)