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 <[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]>
  • Loading branch information
jasnell authored and targos committed May 1, 2021
1 parent cb632e4 commit 92348a9
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 @@ -1608,10 +1608,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 @@ -1632,6 +1635,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 @@ -434,9 +434,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 92348a9

Please sign in to comment.