Skip to content

Instantly share code, notes, and snippets.

@avidal
Created May 15, 2012 22:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avidal/2705513 to your computer and use it in GitHub Desktop.
Save avidal/2705513 to your computer and use it in GitHub Desktop.
/*
Example that utilizes FileSystem API and Web Workers.
Creates a lib.js and worker.js in a temporary file system, then creates a web worker for worker.js that imports lib.js from the local filesystem.
The start of something beautiful?
*/
var fs, liburl, worker = null;
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
console.log(e);
}
function _worker() {
self.onmessage = function(e) {
if(e.data.cmd === "init") {
var liburl = e.data.liburl;
postMessage("Importing lib from " + liburl);
importScripts(liburl);
return;
}
postMessage("PONG: " + e.data);
postMessage("LIB: " + HELLO);
}
}
// Create a temporary 5mb file system, assign the result to the `fs` var
webkitRequestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, step1, errorHandler);
function step1(f) {
console.log('FS created.', f);
fs = f
fs.root.getFile('lib.js', {create:true}, step2, errorHandler);
}
function step2(e) {
console.log('lib.js created', e);
liburl = e.toURL();
e.createWriter(function(writer) {
var bb = new WebKitBlobBuilder();
bb.append('var HELLO="hello, world";');
writer.write(bb.getBlob('text/javascript'));
step3();
}, errorHandler);
}
function step3() {
console.log('lib.js written');
// Create our worker script
fs.root.getFile('worker.js', {create:true}, function(e) {
e.createWriter(function(writer) {
var bb = new WebKitBlobBuilder();
var src = _worker.toString();
src = src.substring("function _worker() {".length, src.length - 1).trim();
bb.append(src);
writer.write(bb.getBlob('text/javascript'));
step4();
}, errorHandler);
}, errorHandler);
}
function step4() {
console.log('worker.js written');
// Pull out the worker file and actually create the worker
fs.root.getFile('worker.js', {}, function(e) {
worker = new Worker(e.toURL());
worker.onmessage = function(e) {
console.log("WORKER: ", e.data, e);
}
console.log('posting messages');
worker.postMessage({ cmd: "init", liburl: liburl });
worker.postMessage("Alright alright alright");
console.log('done.');
}, errorHandler)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment