FileSystemSyncAccessHandle:truncate() 方法

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2023 年 3 月以來,它已在各種瀏覽器中可用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

注意:此功能僅在 專用 Web Worker 中可用。

FileSystemSyncAccessHandle 介面的 truncate() 方法將與該控制代碼關聯的檔案的大小調整為指定的位元組數。

注意: 在規範的早期版本中,close()flush()getSize()truncate() 被錯誤地指定為非同步方法,並且某些瀏覽器舊版本也這樣實現。然而,目前所有支援這些方法的瀏覽器都將它們實現為同步方法。

語法

js
truncate(newSize)

引數

newSize

要將檔案調整到的位元組數。

返回值

無(undefined)。

異常

InvalidStateError DOMException

如果關聯的訪問控制代碼已關閉,或者檔案二進位制資料的修改因其他原因失敗,則會丟擲此錯誤。

QuotaExceededError

如果 newSize 大於檔案的原始大小,並且超過了瀏覽器的 儲存配額,則會丟擲此錯誤。

TypeError

如果底層檔案系統不支援將檔案大小設定為新的大小,則會丟擲此錯誤。

示例

js
async function truncateFile() {
  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Truncate the file to 0 bytes
  accessHandle.truncate(0);

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
}

規範

規範
檔案系統
# api-filesystemsyncaccesshandle-truncate

瀏覽器相容性

另見