Thursday, May 6, 2010

Static HTTP Server in 4 Lines of Fab.js

‹prev | My Chain | next›

Building on my static fab.js file server from last night, I would like to ensure that it only serves up files from the html sub-directory. Right now, a URL that included ../../../etc/passwd might return something that I would prefer it not return:
  (fab.nodejs.fs)
(
function () {
var out = this;
return function (head) {
out({ body: "html/" + head.url.pathname.substr(1) + ".html" });
if (out) out();
};
}
)
Happily, I can make use of a fab.js RegExp app to accomplish this and make my static file server app even shorter:
  (/^\/([_\w]+)$/)
(fab.nodejs.fs)
( fab.tmpl, "html/<%= this %>.html" )
( fab.capture.at, 0 )
Fab.js puts the matched portion of the URL into the capture attribute of the request URL. The fab.capture.at app, with an argument of zero pulls out the zero element from the RegExp matched URL. That gets passed back upstream to the fab.tmpl app which uses micro-templating to build a file path.

I do something similar to serve up Javascript files:
  (/^\/javascript/)
(/^\/([_\w]+)\.js$/)
(fab.nodejs.fs)
( fab.tmpl, "javascript/<%= this %>.js" )
( fab.capture.at, 0 )
(404)
The trailing 404 is the second app for the ternary RegExp that tries to match the .js file. The HTML file app does something similar, but passes on to the next application.

With that, I re-organize some of my javascript and spend the rest of my night readying the code for release on github. No guarantees that it will work, especially with all of the changes fab.js is undergoing currently. Still, hopefully it will be of some use to others.

Day #95

No comments:

Post a Comment