Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
The remove()
method of the FileSystemHandle
interface requests removal of the entry represented by the handle from the underlying file system.
The remove()
method allows you to remove a file or directory directly from its handle. Without this method, you would have to obtain the handle of the parent directory, then call FileSystemDirectoryHandle.removeEntry()
on that to remove it.
You can also call remove()
on the root directory of the Origin Private File System to clear its contents, after which a new empty OPFS is created.
A Promise
that fulfills with a value of undefined
.
Our FileSystemHandle.remove() demo (see the source code) is a file creator app. You can enter text into the <textarea>
and press the "Save file" <button>
, and the app will open a file picker allowing you to save that text onto your local file system in a text file of your choice. You can also choose to delete files you create.
It doesn't allow you to view the content of created files, and it doesn't stay in sync with the underlying file system on page reloads/closes. This means that files created by the app will still exist on the file system if you don't choose to delete them before reloading or closing the tab.
The file picker, file handle, and the file itself if you are creating a new file, are created using window.showSaveFilePicker()
. The text is written to the file via FileSystemFileHandle.createWritable()
.
Once a file is created on the file system, an entry is created in the app (see processNewFile()
in the source code):
- A reference to the file handle is stored in an array called
savedFileRefs
so it can be easily referenced later on. - A list item is added underneath the "Saved files" heading in the UI, with the file name shown alongside a "Delete" button.
When the "Delete" button is pressed, the deleteFile()
function is run, which looks like so:
async function deleteFile(e) {
for (const handle of savedFileRefs) {
if (handle.name === e.target.id + ".txt") {
await handle.remove();
savedFileRefs = savedFileRefs.filter(
(handle) => handle.name !== e.target.id + ".txt",
);
e.target.parentElement.parentElement.removeChild(e.target.parentElement);
}
}
}
Walking through this:
- For each file handle saved in the
savedFileRefs
array, we check its name to see if it matches the id
attribute of the button that triggered the event. - When a match is found, we run
FileSystemHandle.remove()
on that handle to remove the file from the underlying file system. - We also remove the matched handle from the
savedFileRefs
array. - Finally, we remove the list item relating to that file in the UI.