diff --git a/lib/internal/fs.js b/lib/internal/fs.js index 02ba4bbf72baf9..b431cb910c2506 100644 --- a/lib/internal/fs.js +++ b/lib/internal/fs.js @@ -350,11 +350,13 @@ function validateLen(len) { let err; if (!isInt32(len)) { - if (typeof value !== 'number') { + if (typeof len !== 'number') { err = new ERR_INVALID_ARG_TYPE('len', 'number', len); - } else { - // TODO(BridgeAR): Improve this error message. + } else if (!Number.isInteger(len)) { err = new ERR_OUT_OF_RANGE('len', 'an integer', len); + } else { + // 2 ** 31 === 2147483648 + err = new ERR_OUT_OF_RANGE('len', '> -2147483649 && < 2147483648', len); } } diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 62da52b38e1dc3..2f8839583202d0 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -190,6 +190,31 @@ function testFtruncate(cb) { ); }); + [-1.5, 1.5].forEach((input) => { + assert.throws( + () => fs.ftruncate(fd, input), + { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError [ERR_OUT_OF_RANGE]', + message: 'The value of "len" is out of range. It must be ' + + `an integer. Received ${input}` + } + ); + }); + + // 2 ** 31 = 2147483648 + [2147483648, -2147483649].forEach((input) => { + assert.throws( + () => fs.ftruncate(fd, input), + { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError [ERR_OUT_OF_RANGE]', + message: 'The value of "len" is out of range. It must be ' + + `> -2147483649 && < 2147483648. Received ${input}` + } + ); + }); + fs.ftruncate(fd, undefined, common.mustCall(function(err) { assert.ifError(err); assert(fs.readFileSync(file5).equals(Buffer.from('')));