Skip to content

Commit b38d6b4

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 67ac6b3 commit b38d6b4

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

doc/api/fs.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,8 @@ try {
398398
If the file previously was shorter than `len` bytes, it is extended, and the
399399
extended part is filled with null bytes (`'\0'`):
400400
401+
If `len` is negative then `0` will be used.
402+
401403
#### `filehandle.utimes(atime, mtime)`
402404
<!-- YAML
403405
added: v10.0.0
@@ -2292,6 +2294,8 @@ open('temp.txt', 'r+', (err, fd) => {
22922294
If the file previously was shorter than `len` bytes, it is extended, and the
22932295
extended part is filled with null bytes (`'\0'`):
22942296
2297+
If `len` is negative then `0` will be used.
2298+
22952299
### `fs.futimes(fd, atime, mtime, callback)`
22962300
<!-- YAML
22972301
added: v0.4.2

lib/fs.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -810,6 +810,7 @@ function truncate(path, len, callback) {
810810
}
811811

812812
validateInteger(len, 'len');
813+
len = MathMax(0, len);
813814
callback = maybeCallback(callback);
814815
fs.open(path, 'r+', (er, fd) => {
815816
if (er) return callback(er);

test/parallel/test-fs-truncate.js

Lines changed: 16 additions & 0 deletions
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)