Reputation: 5020
I am new in Node/Express
. I am trying to build a static website using Express. I have an assets directory and some pages on the root directory of the project. By googling, got some resources there I got a statement like this:
app.use('/assets', express.static(__dirname + '/assets'));
I know about __dirname
is a current working directory and app.use()
acts as a middleware function, unlike app.get()
and so on. By searching about express.static
got documentation link Serving static files in Express
But I am unclear and confused. I hope someone will be able to help me and thanks in advance.
Upvotes: 8
Views: 8874
Reputation: 21
The app.use(express.static('assets')) code is used to serve static files such as images, CSS files, and JavaScript files in an Express app. The express.static middleware function is used to expose a directory or a file to a particular URL so its contents can be publicly accessed. In this case, the assets directory is exposed to the /assets URL.
For example, if you have an image file named image.jpg in the assets directory, you can access it via the URL
http://localhost:3000/assets/image.jpg.
Upvotes: 2
Reputation: 22949
express.static
exposes a directory or a file to a particular URL so it's contents can be publicly accessed.
From your example:
app.use('/assets', express.static(__dirname + '/assets'));
Assuming the /assets
directory contains 2 images, foo.jpg
and bar.jpg
then you can simply access them at:
There's nothing more to it.
Upvotes: 19