Reputation: 801
What's the difference between
express.static(__dirname + '/static')
and
express.static(path.join(__dirname, '/static'))
And which one i should use for serving the static files
Upvotes: 0
Views: 1527
Reputation: 2610
__dirname
is a global variable in Node.js which is:
The directory name of the current module. more read
i.e
console.log(__dirname);
// Prints: /Users/mjr
you can reach it from anywhere in the app.
path.join()
is a function of nodes' Path
module which:
joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
i.e
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'
Both of your examples produce the same string (in this case!).
BUT using Path.join
will help you take care of constructing the path from different resources or other cases alike eliminating unnecessary delimiters.
i.e
// with Path.join() => say if your platform specific separator is "/"
path.join('/a','b'); // will produce '/a/b'
path.join('\a','/b'); // will produce '/a/b'
path.join('a','\b'); // will produce 'a/b'
which also indicates that express.static(path.join(__dirname, '/static'))
can also be written like this:
express.static(path.join(__dirname, 'static'))
Another example:
express.static(`${__dirname}/${static_path}`)
This can produce problems if you aren't sure about the resource providing static_path
, which can cause an invalid path string.
Upvotes: 1