I ran
node src/app.js
in the mean-to directory
express.static('public')
would work,why?
don't need to specify the path?
what's the rule?
and I know
__dirname+'/../public'`
works just fine.
Just want to make sure the the logic here
I look up the doc http://expressjs.com/en/starter/static-files.html
it says
"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 "
Does that mean
and for safety, better use __dirname to get the absolute path of the directory
Express static uses resolve function from module path
Example using path
:
var p = require('path');
p.resolve('public'); // will return your absolute path for `public` directory
So rules for express static the same as for path#resolve
function
You can see more example in the docs for path module
What's the difference between
p.resolve
and__dirname
?
p.resolve()
resolves to an absolute path
path.resolve('public');
Will return your absolute path for public
' directory(eg " C:\\projects\\myapp\\public
")
path.resolve('src'); // => "C:\projects\myapp\src")
__dirname
- name of the directory(absolute path) from which you're currently running your app
file app.js
console.log(__dirname);
Running node app.js
will print your absolute path for your app, eg " C:\\projects\\myapp
"
You mixed 2 lines in one... And both are necessary:
//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!');
}
Probably, the reason is in running it from directory highter one level than dir with code? Try run it from src:
cd src
node app.js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.