Skip to content

Commit

Permalink
fs: use a default callback for fs.close()
Browse files Browse the repository at this point in the history
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: nodejs#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>
  • Loading branch information
jasnell committed Feb 4, 2021
1 parent fe43bd8 commit 254514c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
8 changes: 7 additions & 1 deletion doc/api/fs.md
Expand Up @@ -1618,10 +1618,13 @@ This is the synchronous version of [`fs.chown()`][].

See also: chown(2).

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

If the `callback` argument is omitted, a default callback function that rethrows
any error as an uncaught exception will be used.

## `fs.closeSync(fd)`
<!-- YAML
added: v0.1.21
Expand Down
6 changes: 5 additions & 1 deletion lib/fs.js
Expand Up @@ -438,7 +438,11 @@ function readFileSync(path, options) {
return buffer;
}

function close(fd, callback) {
function defaultCloseCallback(err) {
if (err != null) throw err;
}

function close(fd, callback = defaultCloseCallback) {
validateInt32(fd, 'fd', 0);
callback = makeCallback(callback);

Expand Down

0 comments on commit 254514c

Please sign in to comment.