14
var express = require('express');
var app = express();
port = process.argv[2] || 8000;

app.configure(function () {
    app.use(
        "/", 
        express.static(__dirname) 
    );
});
app.listen(port);

我删除了下面的这一行,在加载 localhost 时出现错误

app.configure(function () {
        app.use(
            "/", 
            express.static(__dirname) 
        );
    });
  1. app.use 方法有什么作用?
  2. express.static 方法有什么作用?__dirname 指向哪里?
4

2 回答 2

24

app.use 方法有什么作用?

Express 有一个Middleware可以使用 app.configure 配置的,我们可以在其中调用 use app.use()Middleware由路由使用,让我调用 app.use(express.bodyParser())它将此层添加到我的Middleware堆栈中。这确保了对于所有传入的请求,服务器都会解析负责处理的主体Middleware。发生这种情况是因为我们将图层添加到了Middleware.

http://www.senchalabs.org/connect/proto.html#app.use

express.static 方法是什么?__dirname 指向哪里?

该代码创建了一个 Express 服务器,添加了静态Middleware,最后开始监听端口3000或提供的端口。

app.use(
     "/",
     express.static(__dirname)
);

上面的代码等价于下面的代码,让你明白。

app.use(express.static(__dirname + '/')); 

静态中间件处理从目录提供内容。在这种情况下,提供了“根”目录,并且任何内容(HTML、CSS、JavaScript)都将可用。这意味着如果根目录看起来像:

index.html
js - folder
css - folder

有关同一主题的更多参考资料,以下是相关的 stackoverflow 链接。

于 2013-09-19T22:30:39.120 回答
24

In Node, the __dirname is a global object that contains the name of the directory that the executing script resides from. For example, if you are running node script.js from /home/user/env, then __dirname will contain `/home/user/env.

The method app.use() is a function inherited from the Connect framework, which is the framework Express is written on. The method attaches a middleware function to the application stack, which runs every time Express receives a request.

The code you showed mounts a static server to the path / that reads from the directory the script is executing from:

app.use('/', express.static(__dirname));

If you were to change the path to /path, then the static file server will serve static files from that path instead. If you specify no path, then / is used by default.

As for what express.static() does itself, it accepts a path and returns a middleware function that listens on requests. This is how the middleware works:

  1. Check if the request method is GET or HEAD. If neither, ignore the request.
  2. Parse the path and pause the request.
  3. Check if there is a default redirect. If so, redirect with a HTTP 303.
  4. Define the handlers for if a directory or error is encountered.
  5. Pass everything to the send module for MIME identification and file serving.

Here is the static() middleware source from Connect for reference:

exports = module.exports = function(root, options) {
  options = options || {};

  // root required
  if (!root) throw new Error('static() root path required');

  // default redirect
  var redirect = false !== options.redirect;

  return function staticMiddleware(req, res, next) {
    if ('GET' != req.method && 'HEAD' != req.method) return next();
    var path = parse(req).pathname;
    var pause = utils.pause(req);

    function resume() {
      next();
      pause.resume();
    }

    function directory() {
      if (!redirect) return resume();
      var pathname = url.parse(req.originalUrl).pathname;
      res.statusCode = 303;
      res.setHeader('Location', pathname + '/');
      res.end('Redirecting to ' + utils.escape(pathname) + '/');
    }

    function error(err) {
      if (404 == err.status) return resume();
      next(err);
    }

    send(req, path)
      .maxage(options.maxAge || 0)
      .root(root)
      .index(options.index || 'index.html')
      .hidden(options.hidden)
      .on('error', error)
      .on('directory', directory)
      .pipe(res);
  };
};
于 2013-09-20T00:26:08.763 回答