How to serve static file in express js

Leave a Comment
To serve static files such as images, CSS files, and JavaScript files, we can use built-in middleware function in Express. i.e. express.static
we simply need to pass the name of the folder where we have our static files, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a folder named public, we can use below code −
app.use(express.static('public'));
Now, you can load the files that are in the public directory:
http://localhost:3000/images/hello.jpg
http://localhost:3000/css/hello.css
http://localhost:3000/js/hello.js
http://localhost:3000/images/hello.png
http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
To use multiple static assets directories, we can call the express.static middleware function multiple times:
app.use(express.static('public'))
app.use(express.static('files'))
Express looks up the files in the order in which you set the static directories with the express.static middleware function.

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
app.use('/static', express.static('public'))
Now, we can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/hello.jpg
http://localhost:3000/static/css/hello.css
http://localhost:3000/static/js/hello.js
http://localhost:3000/static/images/hello.png
http://localhost:3000/static/hello.html
However, 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:
app.use('/static', express.static(path.join(__dirname, 'public')))


Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .

0 comments:

Post a Comment

Powered by Blogger.