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

时间:2012-04-30 02:18:00

标签: javascript node.js url-routing

我真的很喜欢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样式路由的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

我认为我正在构建您正在寻找的东西。我使用它来提供.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,解析正文等。另外,render的第二个参数总是空的。您可能希望用{layout: xyz}或需要进入渲染页面的泛型变量来填充此内容。

答案 1 :(得分:0)

您可以使用express.static()

例如:

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

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