镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -516,9 +516,13 @@ function readFileAfterOneShot(err, buffer, fd, size, closeErr) {
}

function tryStatSync(fd, isUserFd) {
const stats = binding.fstat(fd, false, undefined, true /* shouldNotThrow */);
if (stats === undefined && !isUserFd) {
fs.closeSync(fd);
let threw = true;
let stats;
try {
stats = binding.fstat(fd, false, undefined, false);
threw = false;
} finally {
if (threw && !isUserFd) fs.closeSync(fd);
}
return stats;
}
Expand Down
2 changes: 1 addition & 1 deletion src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1287,7 +1287,7 @@ static void FStat(const FunctionCallbackInfo<Value>& args) {
AsyncCall(
env, req_wrap_async, args, "fstat", UTF8, AfterStat, uv_fs_fstat, fd);
} else { // fstat(fd, use_bigint, undefined, do_not_throw_error)
bool do_not_throw_error = args[2]->IsTrue();
bool do_not_throw_error = args[3]->IsTrue();
const auto should_throw = [do_not_throw_error](int result) {
return is_uv_error(result) && !do_not_throw_error;
};
Expand Down
35 changes: 35 additions & 0 deletions test/parallel/test-fs-fstat-sync-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Flags: --expose-internals
'use strict';

const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const { internalBinding } = require('internal/test/binding');

const binding = internalBinding('fs');

const badFd = fs.openSync(__filename, 'r');
fs.closeSync(badFd);

// The synchronous fstat binding honours its do_not_throw_error argument.
assert.strictEqual(binding.fstat(badFd, false, undefined, true), undefined);
assert.throws(() => binding.fstat(badFd, false, undefined, false), {
code: 'EBADF',
syscall: 'fstat',
});

// readFileSync() surfaces the fstat error and closes a file descriptor it
// opened itself, but leaves a user-supplied one alone.
fs.openSync = () => badFd;
fs.closeSync = common.mustCall((fd) => {
assert.strictEqual(fd, badFd);
});

assert.throws(() => fs.readFileSync('dummy', 'latin1'), {
code: 'EBADF',
syscall: 'fstat',
});
assert.throws(() => fs.readFileSync(badFd, 'latin1'), {
code: 'EBADF',
syscall: 'fstat',
});