The truncate()
method of the FileSystemWritableFileStream
interface resizes the file associated with the stream to the specified size in bytes.
If the size specified is larger than the current file size the file is padded with null
bytes.
The file cursor is also updated when truncate()
is called. If the offset is smaller than the size, it remains unchanged. If the offset is larger than size, the offset is set to that size. This ensures that subsequent writes do not error.
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.
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.
Next, we write to the stream:
- A text string is written to the stream.
- The
truncate()
method is used to resize the file to 8 bytes. - A second text string is written to the start of the stream, overwriting the first write.
The stream is then closed.
async function saveFile() {
try {
const newHandle = await window.showSaveFilePicker();
const writableStream = await newHandle.createWritable();
await writableStream.write("This is my first file content");
await writableStream.truncate(8);
await writableStream.write("my second file content");
await writableStream.close();
} catch (err) {
console.error(err.name, err.message);
}
}
If you run the above function and then open the resulting file created on disk, you should see the text "This is my second file content".