Consider a web based image editor. You upload the photo, edit whatever is necessary and then download a copy of the modified image.
Wouldn't be better if we could simplify the process and directly update local files, like native apps?
In this post we will be examining how we can achieve this by using the File System Access API.
File System Access API
The File System Access API allows web apps to read or save changes directly to files and folders on the user's device.
In particular, here is what we can do:
- Read a local file
- Specify file types and a starting directory
- Open a directory and enumerating its contents
- Update the contents of a local file
- Create a new file
- Delete files and folders
- Move files around
Note that this feature is not available to all browsers.
Markdown editor
To illustrate some of the FileSystem API features we will be building a Markdown editor to read and write Markdown files from/to the local disk.
Let's go!
Read local files
First let's see how we can read a local file. The following shows a file picker dialog box, and prompts the user to select any markdown file.
A file handle is returned which can be used to read the file contents. Also, we can use the same handle to update its contents later on.
let fileHandle = null;
const options = {
types: [
{
description: 'Markdown Files',
accept: {
'text/markdown': ['.md'],
},
},
],
};
[fileHandle] = await window.showOpenFilePicker(options);
const file = await fileHandle.getFile();
const contents = await file.text();
Update local file
Now let's see how we can update a local file and overwrite its contents. The following uses the file handle returned while reading the file to update its contents.
const contents = '...';
const writable = await fileHandle.createWritable();
await writable.write(contents);
await writable.close();
Demo!
Glue the above code snippets with a Markdown editor and you should be able to load markdown from you local disk, make and persist changes.
Check out this Markdown editor, made using SimpleMDE.
For a better experience, click on the "Open in new Window".
Conclusion
Throughout this post we went through the basics of FileSystem API and examined how it can be used to access and manipulate our local files.
Make sure to follow me on Twitter or dev.to to read more about web development.
Top comments (1)