gpt4 book ai didi

javascript - express.static根路径的规则是什么?

转载 作者:行者123 更新时间:2023-12-03 07:31:02 27 4
gpt4 key购买 nike

我跑了

node src/app.js

在mean-to目录中

express.static('public') 

可以,为什么?

不需要指定路径?

规则是什么?

我知道

__dirname+'/../public'` 

工作得很好。

enter image description here

<小时/>

只是想确定这里的逻辑

我查了一下文档 http://expressjs.com/en/starter/static-files.html

它说

"Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files directly. "

"the path that you provide to the express.static function is relative to the directory from where you launch your node process"

这是否意味着

  1. 如果我在mean-to文件夹中运行node src/app.js --> 使用express.static('public')
  2. 如果我在src文件夹中运行node app.js =>使用express.static('../public')

并且为了安全起见,最好使用__dirname来获取目录的绝对路径

最佳答案

表达静态用途resolve模块 path

中的函数

使用路径的示例:

var p = require('path');
p.resolve('public'); // will return your absolute path for `public` directory

因此,express static 的规则与 path#resolve 函数的规则相同

您可以在 path 的文档中查看更多示例模块

<小时/>

What's the difference between p.resolve and __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

关于javascript - express.static根路径的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35799699/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com