Skip to content

Commit 6b42e65

Browse files
jasnelltargos
authored andcommitted
fs: fixup negative length in fs.truncate
`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 PR-URL: #37483 Reviewed-By: Darshan Sen <raisinten@gmail.com> Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 4a40759 commit 6b42e65

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

doc/api/fs.md

+4
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,8 @@ try {
406406
If the file previously was shorter than `len` bytes, it is extended, and the
407407
extended part is filled with null bytes (`'\0'`):
408408
409+
If `len` is negative then `0` will be used.
410+
409411
#### `filehandle.utimes(atime, mtime)`
410412
<!-- YAML
411413
added: v10.0.0
@@ -2295,6 +2297,8 @@ open('temp.txt', 'r+', (err, fd) => {
22952297
If the file previously was shorter than `len` bytes, it is extended, and the
22962298
extended part is filled with null bytes (`'\0'`):
22972299
2300+
If `len` is negative then `0` will be used.
2301+
22982302
### `fs.futimes(fd, atime, mtime, callback)`
22992303
<!-- YAML
23002304
added: v0.4.2

lib/fs.js

+1
Original file line numberDiff line numberDiff line change
@@ -814,6 +814,7 @@ function truncate(path, len, callback) {
814814
}
815815

816816
validateInteger(len, 'len');
817+
len = MathMax(0, len);
817818
callback = maybeCallback(callback);
818819
fs.open(path, 'r+', (er, fd) => {
819820
if (er) return callback(er);

test/parallel/test-fs-truncate.js

+16
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,19 @@ function testFtruncate(cb) {
280280
);
281281
});
282282
});
283+
284+
{
285+
const file1 = path.resolve(tmp, 'truncate-file-1.txt');
286+
fs.writeFileSync(file1, 'Hi');
287+
fs.truncateSync(file1, -1); // Negative coerced to 0, No error.
288+
assert(fs.readFileSync(file1).equals(Buffer.alloc(0)));
289+
}
290+
291+
{
292+
const file1 = path.resolve(tmp, 'truncate-file-2.txt');
293+
fs.writeFileSync(file1, 'Hi');
294+
// Negative coerced to 0, No error.
295+
fs.truncate(file1, -1, common.mustSucceed(() => {
296+
assert(fs.readFileSync(file1).equals(Buffer.alloc(0)));
297+
}));
298+
}

0 commit comments

Comments
 (0)