Skip to content

Commit 655d196

Browse files
jasnelldanielleadams
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 <jasnell@gmail.com> PR-URL: #37174 Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Darshan Sen <raisinten@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Zijian Liu <lxxyxzj@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 66a14d3 commit 655d196

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

doc/api/fs.md

+7-1
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

+7-2
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)