Skip to content

Commit

Permalink
fs: improve error performance for ftruncateSync
Browse files Browse the repository at this point in the history
PR-URL: #50032
Refs: nodejs/performance#106
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
  • Loading branch information
andremralves authored and targos committed Nov 11, 2023
1 parent 545aa74 commit 57eb06e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 10 deletions.
40 changes: 40 additions & 0 deletions benchmark/fs/bench-ftruncateSync.js
Original file line number Diff line number Diff line change
@@ -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);
}
4 changes: 1 addition & 3 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1136,9 +1136,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() {
Expand Down
12 changes: 5 additions & 7 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1509,25 +1509,23 @@ static void FTruncate(const FunctionCallbackInfo<Value>& 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<Int32>()->Value();

CHECK(IsSafeJsInt(args[1]));
const int64_t len = args[1].As<Integer>()->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);
}
}
Expand Down

0 comments on commit 57eb06e

Please sign in to comment.