filehandle.truncate(len)


截断文件。

【Truncates the file.】

如果文件大于 len 字节,文件中只会保留前 len 字节。

【If the file was larger than len bytes, only the first len bytes will be retained in the file.】

下面的示例仅保留文件的前四个字节:

【The following example retains only the first four bytes of the file:】

import { open } from 'node:fs/promises';

let filehandle = null;
try {
  filehandle = await open('temp.txt', 'r+');
  await filehandle.truncate(4);
} finally {
  await filehandle?.close();
} 

如果文件之前短于“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.】