Skip to content

Commit c82e580

Browse files
bjouhiercjihrig
authored andcommitted
fs: properly handle fd passed to truncate()
Currently, fs.truncate() silently fails when a file descriptor is passed as the first argument. This commit changes this behavior to properly call fs.ftruncate(). PR-URL: nodejs/node-v0.x-archive#9161 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Timothy J Fontaine <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]> Conflicts: lib/fs.js
1 parent 4fcbb8a commit c82e580

File tree

3 files changed

+28
-4
lines changed

3 files changed

+28
-4
lines changed

doc/api/fs.markdown

+2-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,8 @@ Synchronous ftruncate(2).
106106
## fs.truncate(path, len, callback)
107107

108108
Asynchronous truncate(2). No arguments other than a possible exception are
109-
given to the completion callback.
109+
given to the completion callback. A file descriptor can also be passed as the
110+
first argument. In this case, `fs.ftruncate()` is called.
110111

111112
## fs.truncateSync(path, len)
112113

lib/fs.js

+1-3
Original file line numberDiff line numberDiff line change
@@ -679,9 +679,7 @@ fs.renameSync = function(oldPath, newPath) {
679679

680680
fs.truncate = function(path, len, callback) {
681681
if (typeof path === 'number') {
682-
var req = new FSReqWrap();
683-
req.oncomplete = callback;
684-
return fs.ftruncate(path, len, req);
682+
return fs.ftruncate(path, len, callback);
685683
}
686684
if (typeof len === 'function') {
687685
callback = len;

test/parallel/test-fs-truncate-fd.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
var path = require('path');
4+
var fs = require('fs');
5+
var tmp = common.tmpDir;
6+
if (!fs.existsSync(tmp))
7+
fs.mkdirSync(tmp);
8+
var filename = path.resolve(tmp, 'truncate-file.txt');
9+
10+
var success = 0;
11+
12+
fs.writeFileSync(filename, 'hello world', 'utf8');
13+
var fd = fs.openSync(filename, 'r+');
14+
fs.truncate(fd, 5, function(err) {
15+
assert.ok(!err);
16+
assert.equal(fs.readFileSync(filename, 'utf8'), 'hello');
17+
success++;
18+
});
19+
20+
process.on('exit', function() {
21+
fs.closeSync(fd);
22+
fs.unlinkSync(filename);
23+
assert.equal(success, 1);
24+
console.log('ok');
25+
});

0 commit comments

Comments
 (0)