Skip to content

Commit 92348a9

Browse files
jasnelltargos
authored andcommitted
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 cb632e4 commit 92348a9

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
@@ -1608,10 +1608,13 @@ This is the synchronous version of [`fs.chown()`][].
16081608

16091609
See also: chown(2).
16101610

1611-
## `fs.close(fd, callback)`
1611+
## `fs.close(fd[, callback])`
16121612
<!-- YAML
16131613
added: v0.0.2
16141614
changes:
1615+
- version: REPLACEME
1616+
pr-url: https://github.com/nodejs/node/pull/37174
1617+
description: A default callback is now used if one is not provided.
16151618
- version: v10.0.0
16161619
pr-url: https://github.com/nodejs/node/pull/12562
16171620
description: The `callback` parameter is no longer optional. Not passing
@@ -1632,6 +1635,9 @@ to the completion callback.
16321635
Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
16331636
through any other `fs` operation may lead to undefined behavior.
16341637

1638+
If the `callback` argument is omitted, a default callback function that rethrows
1639+
any error as an uncaught exception will be used.
1640+
16351641
## `fs.closeSync(fd)`
16361642
<!-- YAML
16371643
added: v0.1.21

lib/fs.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -434,9 +434,14 @@ function readFileSync(path, options) {
434434
return buffer;
435435
}
436436

437-
function close(fd, callback) {
437+
function defaultCloseCallback(err) {
438+
if (err != null) throw err;
439+
}
440+
441+
function close(fd, callback = defaultCloseCallback) {
438442
validateInt32(fd, 'fd', 0);
439-
callback = makeCallback(callback);
443+
if (callback !== defaultCloseCallback)
444+
callback = makeCallback(callback);
440445

441446
const req = new FSReqCallback();
442447
req.oncomplete = callback;

0 commit comments

Comments
 (0)