Reputation: 4588
In all the node express tutorials I've read the following syntax is used to create the public directory:
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')))
However the following works just fine:
app.use(express.static('public'))
So why would I use the path module instead ?
Upvotes: 7
Views: 5129
Reputation: 203359
The last example uses a relative path, which will work if you start your app from the directory that has public
as a subdirectory.
However, it will break if you start your app from another directory. Let's assume that your app is located in /path/to/app/directory
but that you start your script while /tmp
is the current (working) directory:
/tmp$ node /path/to/app/directory/app.js
In that situation, Express will try to use /tmp/public
as the location for your static files, which isn't correct.
Using path.join(__dirname, 'public')
will create an absolute path, using the directory where app.js
is located as the base. In the example above, it will resolve to /path/to/app/directory/public
, which will also be valid if you start your script from another working directory.
Upvotes: 14