fs.ftruncate(fd[, len], callback)
fd
<integer>len
<integer> 默认值:0
callback
<Function>err
<Error>
异步的 ftruncate(2)
。
除了可能的异常之外,没有为完成回调提供任何参数。
如果文件描述符引用的文件大于 len
个字节,则文件中将仅保留前 len
个字节。
例如,以下程序仅保留文件的前四个字节:
console.log(fs.readFileSync('temp.txt', 'utf8'));
// 打印: Node.js
//
const fd = fs.openSync('temp.txt', 'r+');
//
fs.ftruncate(fd, 4, (err) => {
assert.ifError(err);
console.log(fs.readFileSync('temp.txt', 'utf8'));
});
// 打印: Node
如果文件先前小于 len
个字节,则将其扩展,并且扩展部分将使用空字节('\0'
)填充:
console.log(fs.readFileSync('temp.txt', 'utf8'));
// 打印: Node.js
//
const fd = fs.openSync('temp.txt', 'r+');
//
fs.ftruncate(fd, 10, (err) => {
assert.ifError(err);
console.log(fs.readFileSync('temp.txt'));
});
// 打印: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>
//
fd
<integer>len
<integer> Default:0
callback
<Function>err
<Error>
Asynchronous ftruncate(2)
. No arguments other than a possible exception are
given to the completion callback.
If the file referred to by the file descriptor was larger than len
bytes, only
the first len
bytes will be retained in the file.
For example, the following program retains only the first four bytes of the file:
console.log(fs.readFileSync('temp.txt', 'utf8'));
// Prints: Node.js
// get the file descriptor of the file to be truncated
const fd = fs.openSync('temp.txt', 'r+');
// Truncate the file to first four bytes
fs.ftruncate(fd, 4, (err) => {
assert.ifError(err);
console.log(fs.readFileSync('temp.txt', 'utf8'));
});
// Prints: Node
If the file previously was shorter than len
bytes, it is extended, and the
extended part is filled with null bytes ('\0'
):
console.log(fs.readFileSync('temp.txt', 'utf8'));
// Prints: Node.js
// get the file descriptor of the file to be truncated
const fd = fs.openSync('temp.txt', 'r+');
// Truncate the file to 10 bytes, whereas the actual size is 7 bytes
fs.ftruncate(fd, 10, (err) => {
assert.ifError(err);
console.log(fs.readFileSync('temp.txt'));
});
// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>
// ('Node.js\0\0\0' in UTF8)
The last three bytes are null bytes ('\0'
), to compensate the over-truncation.