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.
In Express, app. use(express. static()) adds a middleware for serving static files to your Express app. For example, suppose you have the below public directory in your project: $ ls -l public/ total 48 -rw-r--r-- 1 ubuntu ubuntu 1666 Mar 12 14:17 home.css -rw-r--r--@ 1 ubuntu ubuntu 17092 Mar 12 14:17 logo.png $
You need express. static so your server can serve files that aren't being generated on the fly. It handles all the file loading and prevents path traversal attacks.
Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.
What Are Static Files? Static files are files that don't change when your application is running. These files do a lot to improve your application, but they aren't dynamically generated by your Python web server like a usual HTML response.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With