FileSystemWritableFileStream: write() 方法
注意:此功能在 Web Workers 中可用。
write() 方法是 FileSystemWritableFileStream 介面的一個方法,它將內容寫入呼叫該方法的檔案的當前檔案指標偏移量處。
在流關閉之前,實際檔案磁碟上不會寫入任何更改。更改通常寫入臨時檔案。此方法還可用於在流中查詢位元組點並截斷以修改檔案包含的總位元組數。
語法
js
write(data)
引數
data-
可以是以下之一
- 要寫入的檔案資料,形式為
ArrayBuffer、TypedArray、DataView、Blob或字串。 - 包含以下屬性的物件:
type-
一個字串,可以是
"write"、"seek"或"truncate"之一。 data-
要寫入的檔案資料。可以是
ArrayBuffer、TypedArray、DataView、Blob或字串。如果type設定為"write",則此屬性是必需的。 position-
如果使用
"seek"型別,則當前檔案指標應移動到的位元組位置。如果type設定為"write",也可以設定此項,在這種情況下,寫入將從指定位置開始。 size-
一個表示流應包含的位元組數的數字。如果
type設定為"truncate",則此屬性是必需的。
- 要寫入的檔案資料,形式為
返回值
一個返回 undefined 的 Promise。
異常
NotAllowedErrorDOMException-
如果
PermissionStatus.state不是granted,則會丟擲此異常。 QuotaExceededError-
如果檔案的新大小大於檔案的原始大小,並且超出了瀏覽器的 儲存配額,則丟擲此異常。
TypeError-
如果
data為 undefined,或者position或size無效,則丟擲此異常。
示例
以下非同步函式開啟“儲存檔案”選擇器,一旦選擇了檔案,它會返回一個 FileSystemFileHandle。從中,使用 FileSystemFileHandle.createWritable() 方法建立可寫流。
然後將文字字串寫入流,隨後關閉流。
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 file content");
// close the file and write the contents to disk.
await writableStream.close();
} catch (err) {
console.error(err.name, err.message);
}
}
以下示例顯示了可以傳遞到 write() 方法中的不同選項。
js
// just pass in the data (no options)
writableStream.write(data);
// writes the data to the stream from the determined position
writableStream.write({ type: "write", position, data });
// updates the current file cursor offset to the position specified
writableStream.write({ type: "seek", position });
// resizes the file to be size bytes long
writableStream.write({ type: "truncate", size });
規範
| 規範 |
|---|
| 檔案系統 # api-filesystemwritablefilestream-write |
瀏覽器相容性
載入中…