--- url: "https://web.dev/articles/filesystem-sync" titulek: "The synchronous FileSystem API for workers | Articles | web.dev" h1: "The synchronous FileSystem API for workers Stay organized with collections Save and categorize content based on your preferences." popis: "" jazyk: "en" kanonicka: "https://web.dev/articles/filesystem-sync" drobecky: ["Articles", "The synchronous FileSystem API for workers"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 03:33:03" znaku: 14666 slov: 1973 kodovani: "iso-8859-2" sha256: "ea5a273303f67dc66070927bcd25bac308f00231dbe60412d49fc4f4b9d65fa3" --- The synchronous FileSystem API for workers Stay organized with collections Save and categorize content based on your preferences. Eric Bidelman Introduction The HTML5 [FileSystem API](http://dev.w3.org/2009/dap/file-system/file-dir-sys.html) and [Web Workers](http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html) are massively powerful in their own regard. The FileSystem API finally brings hierarchical storage and file I/O to web applications and Workers bring true asynchronous 'multi-threading' to JavaScript. However, when you use these APIs together, you can build some truly interesting apps. This tutorial provides a guide and code examples for leveraging the HTML5 FileSystem inside of a Web Worker. It assumes a working knowledge of both APIs. If you're not quite ready to dive in or are interested in learning more about those APIs, read two great tutorials that discuss the basics: [Exploring the FileSystem APIs](https://www.html5rocks.com/tutorials/file/filesystem/) and [Basics of Web Workers](https://www.html5rocks.com/tutorials/workers/basics/). Synchronous vs. Asynchronous APIs Asynchronous JavaScript APIs can be tough to use. They're large. They're complex. But what's most frustrating is that they offer plenty of opportunities for things to go wrong. The last thing you want to deal with is layering on a complex asynchronous API (FileSystem) in an already asynchronous world (Workers)! The good news is that the [FileSystem API](http://dev.w3.org/2009/dap/file-system/file-dir-sys.html) defines a synchronous version to ease the pain in Web Workers. For the most part, the synchronous API is exactly the same as its asynchronous cousin. The methods, properties, features, and functionality will be familiar. The major deviations are: The synchronous API can only be used within a Web Worker context, whereas the asynchronous API can be used in and out of a Worker. Callbacks are out. API methods now return values. The global methods on the window object (`requestFileSystem()` and `resolveLocalFileSystemURL()`) become `requestFileSystemSync()` and `resolveLocalFileSystemSyncURL()`. Apart from these exceptions, the APIs are the same. OK, we're good to go! Requesting a filesystem A web application obtains access to the synchronous filesystem by requesting a `LocalFileSystemSync` object from within a Web Worker. The `requestFileSystemSync()` is exposed to the Worker's global scope: `var fs = requestFileSystemSync(TEMPORARY, 1024*1024 /*1MB*/);` Notice the new return value now that we're using the synchronous API as well as the absence of success and error callbacks. As with the normal FileSystem API, methods are prefixed at the moment: `self.requestFileSystemSync = self.webkitRequestFileSystemSync || self.requestFileSystemSync;` Dealing with quota Currently, it's not possible to [request `PERSISTENT` quota](https://www.html5rocks.com/tutorials/file/filesystem/#toc-requesting-quota) in a Worker context. I recommend taking care of quota issues outside of Workers. The process could look like something this: worker.js: Wrap any FileSystem API code in a `try/catch` so any `QUOTA_EXCEED_ERR` errors are caught. worker.js: If you catch a `QUOTA_EXCEED_ERR`, send a `postMessage('get me more quota')` back to the main app. main app: Go through the `window.webkitStorageInfo.requestQuota()` dance when #2 is received. main app: After the user grants more quota, send `postMessage('resume writes')` back to the worker to inform it of additional storage space. That's a fairly involved workaround, but it should work. See [requesting quota](https://www.html5rocks.com/tutorials/file/filesystem/#toc-requesting-quota) for more information on using `PERSISTENT` storage with the FileSystem API. Working with files and directories The synchronous version of `getFile()` and `getDirectory()` return a `FileEntrySync` and `DirectoryEntrySync`, respectively. For example, the following code creates an empty file called "log.txt" in the root directory. `var fileEntry = fs.root.getFile('log.txt', {create: true});` The following creates a new directory in the root folder. `var dirEntry = fs.root.getDirectory('mydir', {create: true});` Handling errors If you've never had to debug Web Worker code, I envy you! It can be a real pain to figure out what is going wrong. The lack of error callbacks in the synchronous world makes dealing with problems trickier than they should be. If we add the general complexity of debugging Web Worker code, you'll be frustrated in no time. One thing that can make life easier is to wrap all of your relevant Worker code in a try/catch. Then, if any errors occur, forward the error to the main app using `postMessage()`: `function onError(e) { postMessage('ERROR: ' + e.toString()); } try { // Error thrown if "log.txt" already exists. var fileEntry = fs.root.getFile('log.txt', {create: true, exclusive: true}); } catch (e) { onError(e); }` Passing around Files, Blobs, and ArrayBuffers When Web Workers first came on the scene, they only allowed string data to be sent in `postMessage()`. Later, browsers began accepting serializable data, which meant passing a JSON object was possible. Recently however, some browsers like Chrome accept more complex data types to be passed through `postMessage()` using the [structured clone algorithm](https://developer.mozilla.org/DOM/The_structured_clone_algorithm). What does this really mean? It means that it's a heck of a lot easier to pass binary data between main app and the Worker thread. Browsers that support structured cloning for Workers allow you to pass Typed Arrays, `ArrayBuffer`s, `File`s, or `Blob`s into Workers. Although the data is still a copy, being able to pass a `File` means a performance benefit over the former approach, which involved base64ing the file before passing it into `postMessage()`. The following example passes a user-selected list of files to an dedicated Worker. The Worker simply passes through the file list (simple to show the returned data is actually a `FileList`) and the main app reads each file as an `ArrayBuffer`. The sample also uses an improved version of the [inline Web Worker technique](https://www.html5rocks.com/tutorials/workers/basics/#toc-inlineworkers) described in [Basics of Web Workers](https://www.html5rocks.com/tutorials/workers/basics/). `