fs: improve error performance for ftruncateSync

PR-URL: https://github.com/nodejs/node/pull/50032
Refs: https://github.com/nodejs/performance/issues/106
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
This commit is contained in:
André Alves 2023-10-10 19:24:24 -03:00 committed by GitHub
parent ceedb3a509
commit ed49722a8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 10 deletions

View File

@ -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);
}

View File

@ -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() {

View File

@ -1474,7 +1474,7 @@ 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();
@ -1482,17 +1482,15 @@ static void FTruncate(const FunctionCallbackInfo<Value>& args) {
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);
}
}