Difference between app.use(express.static(__dirname + '/public')) and app.use(express.static('public'));

856 Views Asked by At

I wonder if the following two are the same.

(1) app.use(express.static(__dirname + "/public"));
(2) app.use(express.static("public"));

Because I think as long as (2) exists in the express server, the browser can serve up the public folder which is located in the root path and __dirname isn't required.

However, sometimes (2) doesn't work while (1) works such as if I render a ejs file in the dynamic route based on Route parameters.

What exactly is the difference between them?

1

There are 1 best solutions below

0
On

first of all __dirname have 3 usage, you can check documentation:

Making New Directories

To create a new directory in your index.js file, insert __dirname as the first argument to path.join() and the name of the new directory as the second

const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');

fs.mkdirSync(dirPath);

Pointing to Directories

Another unique feature is its ability to point to directories. In your index.js file, declare a variable and pass in the value of __dirname as the first argument in path.join(), and your directory containing static files as the second

express.static(path.join(__dirname, '/public'));

Adding Files to a Directory

You may also add files to an existing directory. In your index.js file, declare a variable and include __dirname as the first argument and the file you want to add as the second If you run the express app from another directory(not root), it’s safer to use the absolute path of the directory that you want to serve, use __dirname

const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/pictures');

fs.openSync(filePath, 'hello.jpeg');

based on your example we can don't use __dirname but if you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve like this

app.use(express.static(__dirname + "/public"));