Created
May 25, 2012 03:25
-
-
Save mschwartz/2785580 to your computer and use it in GitHub Desktop.
Filesystem by Proxy in SilkJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('builtin/fs'), | |
console = require('console'); | |
function DirectoryProxy(path) { | |
return Proxy.create({ | |
get: function(receiver, name) { | |
return fs.readFile(path + '/' + name); | |
}, | |
set: function(receiver, name, value) { | |
fs.writeFile(path + '/' + name, value); | |
return true; | |
}, | |
keys: function() { | |
return fs.readDir(path); | |
}, | |
enumerate: function() { | |
return fs.readDir(path); | |
}, | |
has: function(name) { | |
return fs.exists(path + '/' + name); | |
}, | |
delete: function(name) { | |
fs.unlink(path + '/' + name); | |
} | |
}); | |
} | |
// test it out! | |
var currentDir = new DirectoryProxy('.'); | |
console.dir(Object.keys(currentDir)); | |
currentDir.foo = 'This string written to the file "foo" in the current directory'; | |
console.dir(currentDir.foo); | |
// "foo" should show up in this list: | |
for (var filename in currentDir) { | |
console.log(filename); | |
} | |
console.log('foo exists? ' + ('foo' in currentDir)); | |
delete currentDir.foo; // file "foo" is removed from file system, current directory. | |
console.log('foo exists? ' + ('foo' in currentDir)); | |
-------------------------- | |
Here’s the output when I run it in SilkJS: | |
mschwartz@dionysus:~/src/SilkJS-Sessions$ silkjs ./test2.js | |
./test2.js line 31: | |
(array) : | |
[0] : (string) .git | |
[1] : (string) .idea | |
[2] : (string) bootstrap.js | |
[3] : (string) docroot | |
[4] : (string) README.md | |
[5] : (string) test.js | |
[6] : (string) test2.js | |
./test2.js line 33: | |
(string) This string written to the file "foo" in the current directory | |
.git | |
.idea | |
bootstrap.js | |
docroot | |
foo | |
README.md | |
test.js | |
test2.js | |
foo exists? true | |
foo exists? false | |
mschwartz@dionysus:~/src/SilkJS-Sessions$ ls | |
README.md bootstrap.js docroot test.js test2.js | |
mschwartz@dionysus:~/src/SilkJS-Sessions$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment