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 <jasnell@gmail.com>
Fixes: #35632
  • Loading branch information
jasnell committed Feb 23, 2021
1 parent eed3c72 commit 036c6f4
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/api/fs.md
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
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
7 changes: 7 additions & 0 deletions test/parallel/test-fs-truncate.js
Expand Up @@ -280,3 +280,10 @@ function testFtruncate(cb) {
);
});
});

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

0 comments on commit 036c6f4

Please sign in to comment.