fs.ftruncate(fd[, len], callback)
fd<integer>len<integer> 默认值:0callback<Function>err<Error>
截断文件描述符。完成回调函数除了可能的异常外,不会传入其他参数。
🌐 Truncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
有关更多详细信息,请参阅 POSIX ftruncate(2) 文档。
🌐 See the POSIX ftruncate(2) documentation for more detail.
如果文件描述符指向的文件大于 len 字节,则文件中只会保留前 len 字节。
🌐 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:
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
}); 如果文件之前短于“len”字节,则为扩展文件,且 扩展部分填充空字节(''\0''):
🌐 If the file previously was shorter than len bytes, it is extended, and the
extended part is filled with null bytes ('\0'):
如果 len 为负数,则将使用 0。
🌐 If len is negative then 0 will be used.