[Fixed] What is express.static in Express?

Issue

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.

Solution

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.

Leave a Reply

(*) Required, Your email will not be published