FileSystemWritableFileStream: truncate() 方法
注意:此功能在 Web Workers 中可用。
truncate() 方法是 FileSystemWritableFileStream 介面的一部分,它將與流關聯的檔案大小調整為指定的位元組數。
如果指定的大小大於當前檔案大小,則檔案將用 0x00 位元組進行填充。
呼叫 truncate() 時,檔案指標也會更新。如果偏移量小於指定大小,則保持不變。如果偏移量大於指定大小,則將偏移量設定為該大小。這確保後續寫入不會出錯。
在流關閉之前,不會將任何更改寫入磁碟上的實際檔案。更改通常會寫入臨時檔案。
語法
js
truncate(size)
引數
size-
一個指定要將流調整到的位元組數的數字。
返回值
一個返回 undefined 的 Promise。
異常
NotAllowedErrorDOMException-
如果
PermissionStatus.state不是granted,則會丟擲此異常。 QuotaExceededError-
如果檔案的新大小大於檔案的原始大小,並且超出了瀏覽器的 儲存配額,則會丟擲此錯誤。
TypeError-
如果
size不是數字或未定義,則會丟擲此錯誤。
示例
以下非同步函式開啟“儲存檔案”選擇器,一旦選擇了檔案,它會返回一個 FileSystemFileHandle。從中,使用 FileSystemFileHandle.createWritable() 方法建立可寫流。
接下來,我們將內容寫入流
- 將一個文字字串寫入流。
- 使用
truncate()方法將檔案大小調整為 8 位元組。 - 將第二個文字字串寫入流的開頭,覆蓋第一個寫入的內容。
然後關閉流。
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("This is my first file content");
await writableStream.truncate(8);
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);
}
}
如果執行上述函式,然後開啟磁碟上建立的相應檔案,您應該會看到文字“This is my second file content”。
規範
| 規範 |
|---|
| 檔案系統 # api-filesystemwritablefilestream-truncate |
瀏覽器相容性
載入中…