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: #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 5, 2021
1 parent bf2f2b7 commit 7d0f680
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
8 changes: 7 additions & 1 deletion doc/api/fs.md
Original file line number Diff line number Diff line change
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/37174
description: A default callback is now used 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
9 changes: 7 additions & 2 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -438,9 +438,14 @@ 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);
if (callback !== defaultCloseCallback)
callback = makeCallback(callback);

const req = new FSReqCallback();
req.oncomplete = callback;
Expand Down

0 comments on commit 7d0f680

Please sign in to comment.