在Node中设置基于文件系统的路由

我真的很喜欢PHP提供的简单服务页面,所有的东西都是基于文件系统的。 我想用Node做同样的事情。 我尝试了一个路由设置工作,像这样的意见,但打破了我的公共文件夹:

//using express: app.get('*', function(req, res) { file = req.params[0].substr(1, req.params[0].length); console.log('requesting: ' + file); res.render(file, {locals: { req: req, params: req.query }}); }); 

所以…

在Node中设置基于文件系统/ php风格路由的最佳方式是什么?

我认为,我build立你正在寻找什么。 我使用它来提供.jade文件,显然你可以为你的使用情况调整。

 var url = require('url'); var express = require('express'); var app = express.createServer(); var fs = require('fs'); app.set("view engine", "jade"); app.use(app.router); app.use(express.static(__dirname + '/public')); /** * Generic "get" attempts to route to known JADE files. * If no known JADE files, then we pass routing to next() (should be static). */ app.get('*', function(req, res, next) { var pathname = url.parse(req.url).pathname.toLowerCase(); // make matching case insenstive // First case: with no path name, render the default index.jade if(!pathname) { res.render('index', {}); } // Second case: path ending in '/' points to a folder, use index.jade from that folder else if (pathname === '/' || pathname.charAt(pathname.length-1) === '/' ){ res.render(__dirname + '/views' + pathname + 'index.jade', {}); } // Third case: looks like an actual file, attempt to render else { // Attempt to find the referenced jade file and render that. Note 'views' is default path. fs.stat( (__dirname + "/views" + pathname + '.jade'), function(err, stats){ // There was an error, the file does not exist pass control to the static handler if(err || !stats) { next(); } // We found the file, render it. else{ res.render(pathname.substring(1), {}); } }); } }); app.listen(port); 

注意,应该有更多的app.use()语句来处理cookie,parsing正文等。另外, render的第二个参数总是空的。 您可能需要填写{layout: xyz}或需要进入渲染页面的genericsvariables。

你可以使用express.static()

举些例子:

 app.configure(function(){ app.use(express.static(__dirname + '/public')); }); app.configure(function(){ app.use('/uploads', express.static(PATH_TO_UPLOAD_FOLDER)); });