FileSystemSyncAccessHandle:truncate() 方法

Baseline 2023
Newly available

Since March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

备注: 此特性仅在专用 Web Worker 中可用。

FileSystemSyncAccessHandle 接口的 truncate() 方法用于将与句柄相关联文件的大小调整为指定的字节数。

备注: 在规范早期版本中,close()flush()getSize()truncate() 被错误地规定为异步方法。某些浏览器的旧版本是依照异步方式来实现这些方法的,不过,现今所有支持这些方法的浏览器都将它们实现为同步方法。

语法

js
truncate(newSize)

参数

newSize

要将文件调整到的字节数。

返回值

无(undefined)。

异常

InvalidStateError DOMException

如果相关的访问句柄已经被关闭,或者由于其他原因导致修改文件的二进制数据失败,抛出此异常。

QuotaExceededError DOMException

如果 newSize 大于文件原来的大小并且超出了浏览器的存储配额,抛出此异常。

TypeError

如果底层文件系统不支持将文件大小设为新的大小,抛出此异常。

Examples

js
async function truncateFile() {
  // 获取草稿文件的句柄
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // 获取同步访问句柄
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // 将文件裁剪至 0 字节
  accessHandle.truncate(0);

  // 将更改持久化至磁盘
  accessHandle.flush();

  // 如果完成,请始终关闭 FileSystemSyncAccessHandle
  accessHandle.close();
}

规范

Specification
File System
# api-filesystemsyncaccesshandle-truncate

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
truncate
Synchronous implementation of the truncate() method

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

参见