简体   繁体   English

ExpressJs - express.static(__ dirname)指向哪里?

[英]ExpressJs - where express.static(__dirname) point to?

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

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

I removed this piece of line below and i got an error while loading localhost 我删除了下面的这一行,并在加载localhost时出错

app.configure(function () {
        app.use(
            "/", 
            express.static(__dirname) 
        );
    });
  1. What does the app.use method do?. app.use方法有什么作用?
  2. What does the express.static method do? express.static方法有什么作用? and where does the __dirname points to?. __dirname指向哪里?

In Node, the __dirname is a global object that contains the name of the directory that the executing script resides from. 在Node中, __dirname是一个全局对象,包含执行脚本所在目录的名称。 For example, if you are running node script.js from /home/user/env , then __dirname will contain `/home/user/env . 例如,如果从/home/user/env运行node script.js ,则__dirname将包含`/home/user/env

The method app.use() is a function inherited from the Connect framework, which is the framework Express is written on. 方法app.use()是一个继承自Connect框架的函数,它是写入的框架Express。 The method attaches a middleware function to the application stack, which runs every time Express receives a request. 该方法将中间件功能附加到应用程序堆栈,每次Express收到请求时都会运行该应用程序堆栈。

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. 如果要将路径更改为/path ,则静态文件服务器将从该路径提供静态文件。 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. 至于express.static()本身做什么,它接受一个路径并返回一个监听请求的中间件函数。 This is how the middleware works: 这就是中间件的工作原理:

  1. Check if the request method is GET or HEAD . 检查请求方法是GET还是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 . 如果是这样,请使用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. 将所有内容传递给发送模块以进行MIME标识和文件服务。

Here is the static() middleware source from Connect for reference: 以下是来自Connect的static()中间件源以供参考:

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);
  };
};

What does the app.use method do?. app.use方法有什么作用?

Express has a Middleware which can be configured using app.configure where we can invoke use app.use() . Express有一个Middleware ,可以使用app.configure进行配置,我们可以在其中调用app.use() Middleware is used by routes, lets take i called app.use(express.bodyParser()) which added this layer to my Middleware stack. Middleware由路由使用,让我称为app.use(express.bodyParser()) ,它将此层添加到我的Middleware堆栈。 This ensures that for all incoming requests the server parses the body which Middleware takes cares of. 这确保了对于所有传入请求,服务器解析Middleware负责的主体。 This happens because we added the layer to our Middleware . 发生这种情况是因为我们将图层添加到了Middleware

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

What does the express.static method? express.static方法是什么? and where does the __dirname points to?. __dirname指向哪里?

The code creates an Express server, adds the static Middleware and finally starts listening on port 3000 or provided port. 代码创建一个Express服务器,添加静态Middleware ,最后开始侦听端口3000或提供的端口。

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

The above code is equivalent to below, which you make you understand. 上面的代码相当于下面的代码,您可以通过它理解。

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

The static middleware handles serving up the content from a directory. 静态中间件处理从目录提供内容。 In this case the 'root' directory is served up and any content (HTML, CSS, JavaScript) will be available. 在这种情况下,“root”目录被提供,任何内容(HTML,CSS,JavaScript)都可用。 This means if the root directory looks like: 这意味着如果根目录如下所示:

index.html
js - folder
css - folder

For more references on the same topic, below are stackoverflow links associated. 有关同一主题的更多参考,下面是相关的stackoverflow链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM