Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fs: fixup negative length in fs.truncate #37483

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
16 changes: 16 additions & 0 deletions test/parallel/test-fs-truncate.js
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 cooerced to 0, No error.
jasnell marked this conversation as resolved.
Show resolved Hide resolved
assert(fs.readFileSync(file1).equals(Buffer.alloc(0)));
}

{
const file1 = path.resolve(tmp, 'truncate-file-2.txt');
fs.writeFileSync(file1, 'Hi');
// Negative cooerced to 0, No error.
jasnell marked this conversation as resolved.
Show resolved Hide resolved
fs.truncate(file1, -1, common.mustSucceed(() => {
assert(fs.readFileSync(file1).equals(Buffer.alloc(0)));
}));
}