Fixes #499: Update functionality for fs.truncate (#533)

* Fixes #499: Update functionality for fs.truncate

This change to fs.truncate()'s functionality throws an error when the
length to truncate by is a non-numeric string.

* Refactor numeric type validation

As node implements a helper function to validate numeric values, let's
replicate the same logic to use throughout Filer.
This commit is contained in:
Sean 2018-10-09 13:53:26 -04:00 committed by David Humphrey
parent 2f3c384868
commit 009821290f
3 changed files with 41 additions and 1 deletions

View File

@ -39,6 +39,7 @@ var SuperNode = require('../super-node.js');
var Node = require('../node.js');
var Stats = require('../stats.js');
var Buffer = require('../buffer.js');
const { validateInteger } = require('../shared.js');
/**
* Update node times. Only passed times are modified (undefined times are ignored)
@ -1249,6 +1250,12 @@ function truncate_file(context, path, length, callback) {
if(!fileData) {
return callback(new Errors.EIO('Expected Buffer'));
}
try {
validateInteger(length, 'len');
}
catch (error) {
return callback(error);
}
var data = new Buffer(length);
data.fill(0);
if(fileData) {

View File

@ -1,3 +1,5 @@
var Errors = require('./errors.js');
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
@ -19,8 +21,24 @@ function u8toArray(u8) {
return array;
}
function validateInteger(value, name) {
let err;
if (typeof value !== 'number')
err = new Errors.EINVAL(name, 'number', value);
if (err) {
Error.captureStackTrace(err, validateInteger);
throw err;
}
return value;
}
module.exports = {
guid: guid,
u8toArray: u8toArray,
nop: nop
nop: nop,
validateInteger: validateInteger,
};

View File

@ -10,6 +10,21 @@ describe('fs.truncate', function() {
expect(fs.truncate).to.be.a('function');
});
it('should error when length is not an integer', function(done) {
var fs = util.fs();
var contents = 'This is a file.';
fs.writeFile('/myfile', contents, function(error) {
if(error) throw error;
fs.truncate('/myfile', 'notAnInteger', function(error) {
expect(error).to.exist;
expect(error.code).to.equal('EINVAL');
done();
});
});
});
it('should error when length is negative', function(done) {
var fs = util.fs();
var contents = 'This is a file.';