Access and update local files, from your browser!

Cover image for Access and update local files, from your browser!
Photo by Glenn Carstens-Peters on Unsplash

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.

1let fileHandle = null;
2const options = {
3 types: [
4 {
5 description: 'Markdown Files',
6 accept: {
7 'text/markdown': ['.md'],
8 },
9 },
10 ],
11};
12 
13[fileHandle] = await window.showOpenFilePicker(options);
14 
15const file = await fileHandle.getFile();
16const 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.

1const contents = '...';
2const writable = await fileHandle.createWritable();
3await writable.write(contents);
4await 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
Cover image for Improve collaboration across teams with VSCode

Improve collaboration across teams with VSCode

Next Post
Cover image for Synchronize Postman collections with the API

Synchronize Postman collections with the API

Related Posts