node.js ExpressJs - express.static(__dirname) 指向哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18905872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ExpressJs - where express.static(__dirname) point to?
提问by Kevin
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
我删除了下面的这一行,加载本地主机时出现错误
app.configure(function () {
app.use(
"/",
express.static(__dirname)
);
});
- What does the app.use method do?.
- What does the express.static method do? and where does the __dirname points to?.
- app.use 方法有什么作用?
- express.static 方法有什么作用?__dirname 指向哪里?。
回答by hexacyanide
In Node, the __dirnameis a global object that contains the name of the directory that the executing script resides from. For example, if you are running node script.jsfrom /home/user/env, then __dirnamewill contain `/home/user/env.
在 Node 中,__dirname是一个全局对象,其中包含执行脚本所在目录的名称。例如,如果您node script.js从运行/home/user/env,__dirname则将包含`/home/user/env.
The method app.use()is a function inherited from the Connectframework, 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.
该方法app.use()是从Connect框架继承的一个函数,它是编写 Express 的框架。该方法将一个中间件函数附加到应用程序堆栈,该函数在每次 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. If you specify no path, then /is used by default.
如果您要将路径更改为/path,则静态文件服务器将从该路径提供静态文件。如果未指定路径,则/默认使用。
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:
至于express.static()它自己做什么,它接受一个路径并返回一个侦听请求的中间件函数。这是中间件的工作原理:
- Check if the request method is
GETorHEAD. If neither, ignore the request. - Parse the path and pause the request.
- Check if there is a default redirect. If so, redirect with a
HTTP 303. - Define the handlers for if a directory or error is encountered.
- Pass everything to the sendmodule for MIME identification and file serving.
- 检查请求方法是否为
GET或HEAD。如果两者都不是,则忽略该请求。 - 解析路径并暂停请求。
- 检查是否有默认重定向。如果是这样,请使用
HTTP 303. - 如果遇到目录或错误,定义处理程序。
- 将所有内容传递给发送模块以进行 MIME 识别和文件服务。
Here is the static()middleware source from Connect for reference:
以下是static()Connect的中间件源码,供参考:
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);
};
};
回答by Thalaivar
What does the app.use method do?.
app.use 方法有什么作用?
Express has a Middlewarewhich can be configured using app.configure where we can invoke use app.use(). Middlewareis used by routes, lets take i called
app.use(express.bodyParser())which added this layer to my Middlewarestack. This ensures that for all incoming requests the server parses the body which Middlewaretakes cares of. This happens because we added the layer to our Middleware.
Express 有一个Middleware可以使用 app.configure 配置的,我们可以在其中调用 use app.use()。Middleware由路由使用,让我调用
app.use(express.bodyParser())将这一层添加到我的Middleware堆栈中。这可确保对于所有传入请求,服务器都会解析负责处理的正文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? and where does the __dirname points to?.
express.static 方法是什么?__dirname 指向哪里?。
The code creates an Express server, adds the static Middlewareand finally starts listening on port 3000or 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. This means if the root directory looks like:
静态中间件处理从目录中提供内容。在这种情况下,将提供“根”目录,并且任何内容(HTML、CSS、JavaScript)都将可用。这意味着如果根目录如下所示:
index.html
js - folder
css - folder
For more references on the same topic, below are stackoverflow links associated.
有关同一主题的更多参考,以下是相关联的 stackoverflow 链接。

