Giving the accessibility to a folder in express

In this Hint it shows 2 methods of giving the accessibility to a folder in express

Continuing the discussion from freeCodeCamp Challenge Guide: Serve Static Assets:

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

// Assets at the /public route
app.use("/public", express.static(__dirname + "/public"));

What’s the difference between them both ? and why the second one works but the first one does not work ?

Hello there,

the path that you provide to the express.static function is relative to the directory from where you launch your node process. 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:

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.