Database Reference
In-Depth Information
var url = require('url')
, path = require('path')
, fs = require('fs')
;
function static(srcDir) {
return function(request,response,next) {
if(request.method != "GET") return next();
var p = path.join(process.cwd(),
srcDir,url.parse(request.url).pathname);
fs.exists(p,function(yes) {
if(!yes) return next();
fs.createReadStream(p).pipe(response);
});
}
}
In this example, the static function returns another function configured
with the source directory held in srcDir . This allows it to be used in
connect by calling use(static(”public”)) . Functions contained
within another function are called “inner functions” and have access to
variables in the “outer” function through a feature of JavaScript called
lexical scoping. When a request comes down the chain, first the inner
function checks for a GET method request. If it is not the appropriate
method, then the next function is called to continue the processing chain.
Next,apathtotherequestedfileisconstructedand,iffound,thefileispiped
totheHTTPresponseusingthe pipe methodonNode's ReadStream class.
Notice that the next function is not called. This is because the request chain
should terminate at this point, as a response has been returned to the client.
The express.js Web Framework
Building on connect middleware the same way that Sinatra or Rails
build on Rack in Ruby, express.js is a framework for building
full-fledged web applications. It is designed to support the
Model-View-Controller (MVC) style of web application, which works well
with streaming data applications. Getting started with express.js looks a
lot like starting a connect application:
Search WWH ::




Custom Search