FileSystemWritableFileStream: seek() 方法

基準線 2025
新推出

自 ⁨2025 年 9 月⁩起,此功能適用於最新裝置和瀏覽器版本。此功能可能不適用於較舊的裝置或瀏覽器。

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

注意:此功能在 Web Workers 中可用。

seek() 方法是 FileSystemWritableFileStream 介面的一部分,它會在呼叫該方法時,將當前檔案的游標偏移量更新到指定的位置(以位元組為單位)。

語法

js
seek(position)

引數

position

一個指定檔案開頭位元組位置的數字。

返回值

一個返回 undefinedPromise

異常

NotAllowedError DOMException

如果 PermissionStatus.state 不是 granted,則會丟擲此異常。

TypeError

如果 position 不是數字或未定義,則會丟擲錯誤。

示例

以下非同步函式開啟“儲存檔案”選擇器,一旦選擇了檔案,它會返回一個 FileSystemFileHandle。從中,使用 FileSystemFileHandle.createWritable() 方法建立可寫流。

接下來,我們將內容寫入流

  1. 一個文字字串被寫入流。
  2. seek() 方法用於將游標置於流的開頭。
  3. 第二個文字字串被寫入流的開頭,覆蓋了第一次寫入的內容。

然後關閉流。

js
async function saveFile() {
  try {
    // create a new handle
    const newHandle = await window.showSaveFilePicker();

    // create a FileSystemWritableFileStream to write to
    const writableStream = await newHandle.createWritable();

    // write our file
    await writableStream.write("My first file content");
    await writableStream.seek(0);
    await writableStream.write("My second file content");

    // close the file and write the contents to disk.
    await writableStream.close();
  } catch (err) {
    console.error(err.name, err.message);
  }
}

如果您執行上面的函式,然後開啟在磁碟上建立的生成檔案,您應該會看到文字“My second file content”。

規範

規範
檔案系統
# api-filesystemwritablefilestream-seek

瀏覽器相容性

另見