diff --git a/lib/fs.js b/lib/fs.js index 39f35371393f4a..118d7fe800cbfa 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -35,7 +35,6 @@ const kIoMaxLength = 2 ** 31 - 1; const { ArrayPrototypePush, BigIntPrototypeToString, - MathMax, Number, NumberIsSafeInteger, ObjectCreate, @@ -845,7 +844,11 @@ function ftruncate(fd, len = 0, callback) { } validateInt32(fd, 'fd', 0); validateInteger(len, 'len'); - len = MathMax(0, len); + + if (len < 0) { + throw new ERR_INVALID_ARG_VALUE('len', len); + } + callback = makeCallback(callback); const req = new FSReqCallback(); @@ -856,7 +859,11 @@ function ftruncate(fd, len = 0, callback) { function ftruncateSync(fd, len = 0) { validateInt32(fd, 'fd', 0); validateInteger(len, 'len'); - len = MathMax(0, len); + + if (len < 0) { + throw new ERR_INVALID_ARG_VALUE('len', len); + } + const ctx = {}; binding.ftruncate(fd, len, undefined, ctx); handleErrorFromBinding(ctx); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 418d56c047d4e3..e5965a5b7a7b1f 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -224,13 +224,14 @@ function testFtruncate(cb) { } { - const file6 = path.resolve(tmp, 'truncate-file-6.txt'); - fs.writeFileSync(file6, 'Hi'); - const fd = fs.openSync(file6, 'r+'); - process.on('beforeExit', () => fs.closeSync(fd)); - fs.ftruncate(fd, -1, common.mustSucceed(() => { - assert(fs.readFileSync(file6).equals(Buffer.from(''))); - })); + assert.throws( + () => fs.ftruncate(fd, -1), + { + code: 'ERR_INVALID_ARG_VALUE', + name: /(TypeError|RangeError)/, + message: 'The argument \'len\' is invalid. Received -1' + } + ); } {