FileSystemWritableFileStream: write() method
The write()
method of the FileSystemWritableFileStream
interface writes content into the file the method is called on, at the current file cursor offset.
No changes are written to the actual file on disk until the stream has been closed. Changes are typically written to a temporary file instead. This method can also be used to seek to a byte point within the stream and truncate to modify the total bytes the file contains.
Syntax
Parameters
-
data
-
Can be one of the following:
- The file data to write, in the form of an
ArrayBuffer
, TypedArray
, DataView
, Blob
, or string.
- An object containing the following properties:
-
type
-
A string that is one of "write"
, "seek"
, or "truncate"
.
-
data
-
The file data to write. Can be an ArrayBuffer
, TypedArray
, DataView
, Blob
, or string. This property is required if type
is set to "write"
.
-
position
-
The byte position the current file cursor should move to if type "seek"
is used. Can also be set if type
is "write"
, in which case the write will start at the specified position.
-
size
-
A number representing the number of bytes the stream should contain. This property is required if type
is set to "truncate"
.
Return value
A Promise
that returns undefined
.
Exceptions
NotAllowedError
DOMException
-
Returned if PermissionStatus.state
is not granted
.
-
TypeError
-
Returned if data is undefined, or if position
or size
aren't valid.
InvalidStateError
DOMException
-
Returned if the specified position
is larger than the length of the file data in bytes.
Examples
The following asynchronous function opens the 'Save File' picker, which returns a FileSystemFileHandle
once a file is selected. From this, a writable stream is created using the FileSystemFileHandle.createWritable()
method.
A text string is then written to the stream, which is subsequently closed.
async function saveFile() {
try {
const newHandle = await window.showSaveFilePicker();
const writableStream = await newHandle.createWritable();
await writableStream.write("This is my file content");
await writableStream.close();
} catch (err) {
console.error(err.name, err.message);
}
}
The following examples show different options that can be passed into the write()
method.
writableStream.write(data);
writableStream.write({ type: "write", position, data });
writableStream.write({ type: "seek", position });
writableStream.write({ type: "truncate", size });
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
write |
86 |
86 |
111 |
No |
72 |
No |
No |
No |
111 |
No |
No |
No |
See also