![](/img/trans.png)
[英]What is the difference between “views” path and the path used in express.static?
[英]What is the rule for express.static root path?
我跑了
node src/app.js
在均值目录中
express.static('public')
会工作,为什么呢?
不需要指定路径?
有什么规则?
而且我知道
__dirname+'/../public'`
效果很好。
只想确保这里的逻辑
我在http://expressjs.com/en/starter/static-files.html上查找了文档
它说
“将包含静态资产的目录的名称传递给express.static中间件函数,以开始直接提供文件。”
“您提供给express.static函数的路径是相对于您启动节点进程的目录的 ”
这是否意味着
为了安全起见,最好使用__dirname获取目录的绝对路径
Express static使用模块path
resolve函数
使用path
示例:
var p = require('path');
p.resolve('public'); // will return your absolute path for `public` directory
因此,用于表达静态的规则与用于path#resolve
函数的规则相同
您可以在文档中查看路径模块的更多示例
p.resolve
和__dirname
什么__dirname
?
p.resolve()
解析为绝对路径
path.resolve('public');
将返回public
'目录的绝对路径(例如“ C:\\projects\\myapp\\public
”)
path.resolve('src'); // => "C:\projects\myapp\src")
__dirname
您当前从中运行应用程序的目录名称(绝对路径)
文件app.js
console.log(__dirname);
运行node app.js
将为您的应用程序打印您的绝对路径,例如“ C:\\projects\\myapp
”
您将两行混合在一起...两者都是必要的:
//This line is to say that the statics files are in public
app.use(express.static(__dirname + "/public"));
//This another line is to say that when call the route "/" render a page
app.get("/", function (req, res) {
res.send('Hello World!');
}
可能是因为在目录中使用代码比dir从目录更高一级运行它? 尝试从src运行它:
cd src
node app.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.