`hello-express` template should use `__dirname` in `express.static`

In the https://glitch.com/edit/#!/hello-express template (which is in the drop-down menu when you click “New Project”) this:

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

Should be this:

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

I found this out when deploying a glitch repo to my own server and running it with PM2.

__dirname is correctly used on this line of the template:

response.sendFile(__dirname + "/views/index.html");

Which makes me think that the lack of __dirname in the express.static line is definitely a mistake.

1 Like

I don’t think that’s necessary because it works perfectly fine and also, the documentation for static files in Express (https://expressjs.com/en/starter/static-files.html) already has such an example, and in that

For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public :

app.use(express.static('public'))

And that just works perfectly fine!

2 Likes

to extend on khalby’s just posted answer,
it is also recommended to use

express.static("/public")

especially on a vm like glitch, so, any way is perfectly fine to use

We’re in the process of updating hello-express with the latest versions of modules and some updated code structure, so this feedback is right on time! @J-Tech-Foundation and @joe, I’m trying to understand what the benefits of adding __dirname or the leading / are, can you share some more details?

1 Like

here is the information:

__dirname is ( and i think, have not hopped on the actual editor today, so my mind is blank ) /user/app/
which, without sudo, or root, “/” will equal to that of the base directory of the project, that should explain all

oh, ~/ is the same as / in things like fs and express, so, yea…
all i can explain

1 Like

@potch Here’s a simple explanation from stack overflow:

image

The express.js docs explain why it’s safer to use __dirname:

image

It’s not a huge deal for the average user of Glitch, but it can be dangerous for those who export their code to put it on their own server (and run it with PM2, for example), because you can end up serving a directory that you didn’t intend to. This is probably why the original author of the hello-express template used __dirname for response.sendFile(...). I think they just forgot to add it for the express.static(...) call.

1 Like