Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is express.static in Express?

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.

like image 341
Bablu Ahmed Avatar asked Oct 26 '18 06:10

Bablu Ahmed


People also ask

What is Express static in Express JS?

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 $

Why Express static is used?

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.

What is static folder in Express?

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 is a static file?

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.


1 Answers

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:

  • http://your-domain.com/assets/foo.jpg
  • http://your-domain.com/assets/bar.jpg

There's nothing more to it.

like image 83
nicholaswmin Avatar answered Oct 16 '22 20:10

nicholaswmin