Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use path.join() instead of just static('public')

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 ?

like image 848
William Avatar asked Aug 26 '15 12:08

William


People also ask

Why do we use path join?

The path. join() method is used to join a number of path-segments using the platform-specific delimiter to form a single path. The final path is normalized after the joining takes place. The path-segments are specified using comma-separated values.

What does the join () method of node's path module do?

The path. join() method joins the specified path segments into one path. You can specify as many path segments as you like. The specified path segments must be strings, separated by comma.

How does PATH join work?

The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. Zero-length path segments are ignored. If the joined path string is a zero-length string then '.' will be returned, representing the current working directory.

What is the difference between path join and path resolve?

The path. resolve() method resolves a sequence of paths or path segments into an absolute path. The path. join() method joins all given path segments together using the platform specific separator as a delimiter, then normalizes the resulting path.


1 Answers

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.

like image 133
robertklep Avatar answered Oct 21 '22 06:10

robertklep