◐ Shell
clean mode source ↗

fs: add length validation to fs.truncate() · nodejs/node@469baa0

Original file line numberDiff line numberDiff line change

@@ -85,6 +85,7 @@ const {

8585

} = require('internal/constants');

8686

const {

8787

isUint32,

88+

validateInteger,

8889

validateInt32,

8990

validateUint32

9091

} = require('internal/validators');

@@ -746,6 +747,7 @@ fs.truncate = function(path, len, callback) {

746747

len = 0;

747748

}

748749
750+

validateInteger(len, 'len');

749751

callback = maybeCallback(callback);

750752

fs.open(path, 'r+', function(er, fd) {

751753

if (er) return callback(er);

Original file line numberDiff line numberDiff line change

@@ -179,6 +179,16 @@ function testFtruncate(cb) {

179179

process.on('exit', () => fs.closeSync(fd));

180180
181181

['', false, null, {}, []].forEach((input) => {

182+

assert.throws(

183+

() => fs.truncate(file5, input, common.mustNotCall()),

184+

{

185+

code: 'ERR_INVALID_ARG_TYPE',

186+

name: 'TypeError [ERR_INVALID_ARG_TYPE]',

187+

message: 'The "len" argument must be of type number. ' +

188+

`Received type ${typeof input}`

189+

}

190+

);

191+
182192

assert.throws(

183193

() => fs.ftruncate(fd, input),

184194

{

@@ -191,6 +201,16 @@ function testFtruncate(cb) {

191201

});

192202
193203

[-1.5, 1.5].forEach((input) => {

204+

assert.throws(

205+

() => fs.truncate(file5, input),

206+

{

207+

code: 'ERR_OUT_OF_RANGE',

208+

name: 'RangeError [ERR_OUT_OF_RANGE]',

209+

message: 'The value of "len" is out of range. It must be ' +

210+

`an integer. Received ${input}`

211+

}

212+

);

213+
194214

assert.throws(

195215

() => fs.ftruncate(fd, input),

196216

{