diff --git a/benchmark/fs/bench-ftruncateSync.js b/benchmark/fs/bench-ftruncateSync.js new file mode 100644 index 00000000000000..a02686ffd901b3 --- /dev/null +++ b/benchmark/fs/bench-ftruncateSync.js @@ -0,0 +1,40 @@ +'use strict'; + +const common = require('../common'); +const fs = require('fs'); +const tmpdir = require('../../test/common/tmpdir'); +tmpdir.refresh(); + +const path = tmpdir.resolve(`new-file-${process.pid}`); +fs.appendFileSync(path, 'Some content.'); + +const bench = common.createBenchmark(main, { + type: ['invalid', 'valid'], + n: [1e4], +}); + +function main({ n, type }) { + let fd; + + switch (type) { + case 'invalid': + fd = 1 << 30; + break; + case 'valid': + fd = fs.openSync(path, 'r+'); + break; + default: + throw new Error('Invalid type'); + } + + bench.start(); + for (let i = 0; i < n; i++) { + try { + fs.ftruncateSync(fd, 4); + } catch { + // do nothing + } + } + bench.end(n); + if (type === 'valid') fs.closeSync(fd); +} diff --git a/lib/fs.js b/lib/fs.js index 684ac76a12ce50..653e472202d183 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1138,9 +1138,7 @@ function ftruncateSync(fd, len = 0) { fd = getValidatedFd(fd); validateInteger(len, 'len'); len = MathMax(0, len); - const ctx = {}; - binding.ftruncate(fd, len, undefined, ctx); - handleErrorFromBinding(ctx); + binding.ftruncate(fd, len); } function lazyLoadCp() { diff --git a/src/node_file.cc b/src/node_file.cc index 778e9139e4dc93..1e9f3cad0d324f 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -1474,7 +1474,7 @@ static void FTruncate(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); const int argc = args.Length(); - CHECK_GE(argc, 3); + CHECK_GE(argc, 2); CHECK(args[0]->IsInt32()); const int fd = args[0].As()->Value(); @@ -1482,17 +1482,15 @@ static void FTruncate(const FunctionCallbackInfo& args) { CHECK(IsSafeJsInt(args[1])); const int64_t len = args[1].As()->Value(); - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - if (req_wrap_async != nullptr) { + if (argc > 2) { + FSReqBase* req_wrap_async = GetReqWrap(args, 2); FS_ASYNC_TRACE_BEGIN0(UV_FS_FTRUNCATE, req_wrap_async) AsyncCall(env, req_wrap_async, args, "ftruncate", UTF8, AfterNoArgs, uv_fs_ftruncate, fd, len); } else { - CHECK_EQ(argc, 4); - FSReqWrapSync req_wrap_sync; + FSReqWrapSync req_wrap_sync("ftruncate"); FS_SYNC_TRACE_BEGIN(ftruncate); - SyncCall(env, args[3], &req_wrap_sync, "ftruncate", uv_fs_ftruncate, fd, - len); + SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_ftruncate, fd, len); FS_SYNC_TRACE_END(ftruncate); } }