Skip to content

Commit

Permalink
fs: fixup negative length in fs.truncate
Browse files Browse the repository at this point in the history
`fs.ftruncate`, `fsPromises.truncate`, and `fsPromises.ftruncate`
all adjust negative lengths to 0 before invoking the system call.
`fs.truncate()` was the one outlier.

This "fixes" #35632 but in the
opposite direction than discussed in the issue -- specifically by
removing an EINVAL error from one function rather than adding it to
another.

Signed-off-by: James M Snell <[email protected]>
Fixes: #35632

PR-URL: #37483
Reviewed-By: Darshan Sen <[email protected]>
Reviewed-By: Juan José Arboleda <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
  • Loading branch information
jasnell committed Feb 25, 2021
1 parent ee6c467 commit 148bc33
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/api/fs.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,8 @@ try {
If the file previously was shorter than `len` bytes, it is extended, and the
extended part is filled with null bytes (`'\0'`):
If `len` is negative then `0` will be used.
#### `filehandle.utimes(atime, mtime)`
<!-- YAML
added: v10.0.0
Expand Down Expand Up @@ -2295,6 +2297,8 @@ open('temp.txt', 'r+', (err, fd) => {
If the file previously was shorter than `len` bytes, it is extended, and the
extended part is filled with null bytes (`'\0'`):
If `len` is negative then `0` will be used.
### `fs.futimes(fd, atime, mtime, callback)`
<!-- YAML
added: v0.4.2
Expand Down
1 change: 1 addition & 0 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,7 @@ function truncate(path, len, callback) {
}

validateInteger(len, 'len');
len = MathMax(0, len);
callback = maybeCallback(callback);
fs.open(path, 'r+', (er, fd) => {
if (er) return callback(er);
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-fs-truncate.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,19 @@ function testFtruncate(cb) {
);
});
});

{
const file1 = path.resolve(tmp, 'truncate-file-1.txt');
fs.writeFileSync(file1, 'Hi');
fs.truncateSync(file1, -1); // Negative coerced to 0, No error.
assert(fs.readFileSync(file1).equals(Buffer.alloc(0)));
}

{
const file1 = path.resolve(tmp, 'truncate-file-2.txt');
fs.writeFileSync(file1, 'Hi');
// Negative coerced to 0, No error.
fs.truncate(file1, -1, common.mustSucceed(() => {
assert(fs.readFileSync(file1).equals(Buffer.alloc(0)));
}));
}

0 comments on commit 148bc33

Please sign in to comment.