Skip to content

Instantly share code, notes, and snippets.

@mschwartz
Created May 25, 2012 03:25
Show Gist options
  • Save mschwartz/2785580 to your computer and use it in GitHub Desktop.
Save mschwartz/2785580 to your computer and use it in GitHub Desktop.
Filesystem by Proxy in SilkJS
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