HTML5 File System API Tutorial You Must Know About

This is an elegant HTML5 File System API tutorial among several other web file system API that will make you learn about basic of HTML5 Filesystem API. This Filesystem API or HTML5 File System will let you learn about accessing the user's local file system between web application and desktop.

In previous post we already have discussed a lot about HTML5 including its power, feature and advantages. However, it make us flexible and ease as well as tend to open a door for new possibilities which enables you to implement multimedia accompanied by video and audio APIs, drawing with canvas and miscellaneous. Moreover, out of these tools, today we are going to learn about one more innovative tool and that is the File System API. It enables us to access the user’s local file system in account of a sandboxed section which eventually narrow the gap between web application and desktop even further.

However, in account of this tutorial post HTML5 File System API Tutorial You Must Know About we will learn about the basic of this exciting and novice API of HTML5 by exploring the regular task of filesystem. So, let’s get started.


In bottom line, I would like to add hear that web application in contrast of desktop application are cool but consist one downside that they are unable to organize and interact data in a structured order of folders – a realistic file system. But now this new Filesystem has transformed this. This Filesystem API provide the web applications with controlled access to local Filesystem “sandbox”, where you can read and write files, list and create directories and miscellaneous.

The Filesystem API comes in two distinct versions. First one is asynchronous API, which is obvious for regular applications and another is synchronous API that is reserved to employed with web workers. But in this tutorial we will opt to go with asynchronous API version.

Step 1: Getting Started

The first step towards the direction of obtaining HTML5 Filesystem accessing you are required to send a request for LocalFile System object by employing window.requestFileSystem() global method:

With first two parameters the size and type of the Filesystem has been defined as you want.

There is a PERSISTENT Filesystem which is supposed to be perfect for web applications where it wish to store the user data permanently. It can’t be deleted by browser until the users itself don’t explicit a request. The TEMPORARY Filesystem is suitable for those web application who wish to cache data but can be still operated even web browser delete the Filesystem. The size of Filesystem is expressed in bytes as well as you are supposed to take care of a reasonable upper bound on data quantity you need to store.

It also incorporate a callback function which is considered as a third parameter and is useful to triggered when a user agent deliver a Filesystem. The FileSystem object is its argument. Eventually, we can include an optional function of callback that is supposed to be recalled either after occurrence of any error or a request being denied for a Filesystem. FileError object is its argument. Though this is an optional parameter but is a good practice to designate errors for users as lot of places are there where thing can go wrong.

The Filesystem we aggregated with these functions is directly sits on the containing document origin. All the web applications and document including host, protocol and port from the same origin share a Filesystem. Two applications & documents from distinct origins incorporate completely different and disjoint Filesystem. The Filesystem comes with a limitation of restriction to a single application and unable to access stored data of other applications. It is also desolated from other files on the users’ storage device including hard drive that is a great achievement. The web application don’t comprises any method to “break out” behind the directory of local root or accessing arbitrary files.

Let’s take a look over this example:

This is useful to generate a temporary Filesystem with storage capacity of 5MB. Then it delivers a callback function successfully which is being implemented to access our Filesystem. Moreover, in context of handling errors, if appears an error handler is also incorporated. Here, the comprised function of errorHandler () is too generic. So, you are free to generate a optimized version if you want, which convey an error message to readers:

The obtained Filesystem object is accompanied by a unique name defined by browser as well as root property which is concerned with root directory of the Filesystem. This is referred as a DirectoryEntry object which might be comprises with nested directories which are represented by DirectoryEntry objects. In the Filesystem, each directory contain some files which are represented by FileEntry objects. Further, The DirectoryEntry objects describe the method for getting FileEntry and DirectoryEntry objects by pathname (optionally, they will generate new files and directories in the case you defien a name that doesn’t exist). DirectoryEntry also specify a method of createReader() factory that says a DirectoryReader object towards listing a directory content. The FileEntry class assigns a procedure in order to get the File object which represents the content of a file. Then you can employ a FileReader object to read this file. In order to write content in a file FileEntry designate another procedure to call a FileWriter object.

Step 2: Working with Directories

The first most important thing you are required is to develop some directories or buckets in the FileSystem. As the root directory already exists there, you don’t want to put all your files there. The DirectoryEntry object used to created directories. In the example provided below we are going to generate a directory defined name with Documents withing the root directory.

In order to create or read directories the method employed is the getDirectory (). The first parameters says that you can specify either a path or name as the directory to create or read. Next, for second argument we set to true, because we are going to generate a directory – not read an existing one. Eventually, we include a callback for an error.

Now, we got a directory and proceed further to incorporate a subdirectory. The function is very identical but with one exception: We can transform the first attribute from ‘Documents’ to ‘Documents/Music’. It seems to be very easy, but what in the case you wish to create a subfolder named sky accompanied with two parent folder, Nature and Images withing the folder ‘Documents’. Thus when you will type the path argument ‘Documents/Images/Nature/Sky, you will got an error, as you can’t create a directory in the case when the adjacent parent does not exist. In order to resolve this issue you can create every folder one by one: inside Documents Images, inside Images create Nature folder and inside Nature create Sky. But, it seems to very time consuming and inconvenient process. So, you may opt for a more better solution of creating a function that will be capable to create all folders automatically.

Thus by employing this trick, you are required to assign the complete path stating the directories which you wish to create. Finally, you have created the Sky directory and in addition you can develop other directories and files within this folder.

After accomplishing this now you are supposed to analyze your Filesystem once. In order to read your directory content you will be required to create a DirectoryReader object and employ the method of thereadEntries ().

In the above snippet of code, the isFile and the isDirectory properties are being employed towards achieving a distinct output for files and directories, respectively. In addition, instead of its name only you can also receive the complete path of the entry in account of employing the fullPath property.

There are two different ways to eliminate a DirectoryEntry from the Filesystem which are remove () and removeRecursively(). The first one is used to eliminate a specific given directory only when it is empty. Otherwise, an error will occurred.

When the Music folder incorporate some files within it, then you will have to implement the second method, which is useful to delete the directory with all its contents recursively.

Step 3: Working with Files

Now, as you have learned to create directories let’s colonize them with files. This fragment of code which sits below says about how to create an empty test.txt in the root directory:

The getFile() first argument must be valid which can be relative or absolute path. As for example, you will receive an error while creating a file in the case when the adjacent parent does not exist. Object literal is referred as the second argument that elaborate the function’s behavior when the concerned file does not exist. In this illustration, create:true is obvious that creates the file when the file does not exist and say an error when it does (exclusive: true). On the other end, if create: false, the file is simply retrieved and returned.

Here, putting an empty file shows no significance, so let’s go ahead to include some content to this. You cam employ the FileWriter object towards this endeavor.

With above snippet code, we attempt to fetch the test.txt file, and generate a FileWriter object concerned with it. Next, you may incorporate content inside this just by creating another new BlobBuilder object and by employing the method of write() of FileWriter. Then fetch the FileEntry by calling getFile (). But is not going to return file content. So, in order to read the file content, you are required to implement the FileReader object and the File object.

As, we have incorporated content to your file, but what when you wish to include more content to the file later? In context of appending data to a file which already exist, you are required to employ FileWriter once again. Moreover, you can alter the position of the writer to the end section of the file in account of seek() method. As an argument seek can accepts a byte offset, and designate the position of Filewriter to that offset.

However, in order to remove a file from your Filesystem, simply you are required to call entry.remove(). The zero-parameter callback function is the first argument of this method which is called in the case when the respective file is successfully deleted. An optional error callback is the another argument which is called when any error occurred.

Step 4: Manipulating Files and Directories

DirectoryEntry and FileEntry both share the identical API methods for accomplishing the task of copying, moving and renaming entries. Thus, two methods are available which can be employed to perform these operations which are moveTo() and copyTo(). Both can accept identical parameters exactly:

Parent folder is the first parameter which is useful to copy/move the entry into. The second parameter concerned with an options new name which provide the copied/moved entry, which is exactly required which you are required to copy an entry into the same folder, otherwise, you may receive an error. As, we have already discussed third and fourth parameters earlier.

However, prior to proceed further, Let’s take a look over these simple illustration. In below provided snippet, we will copy the file test.txt from the root to the Documents directory.

The snippet provided below will results in moving test.txt to Document rather than of copying it.

This example is about renaming a test.txt to txt.txt:

Bryan Lazaris

Brayan Lazaris, a web development expert, has been working with HireWebDeveloper for many years. Till now, he has written numerous blogs and articles elucidating the best methods and approaches to process web development brilliantly. His keen interest in researching the smart technique for better web solution has opened the gateway for many businesses to establish a strong foothold in the digital space.