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.
A Promise
that returns undefined
.
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 });