Thursday, May 21, 2020

ExpressJS Serving static files

ExpressJS Serving static files

Serving static files in Express

We can easily serve static files by using the built-in middleware in Express.js. The express.static() method is used to serve static resources such as images, CSS files, and JavaScript files, etc directly by providing the folder name where the static files are stored.

The syntax of the function is,

 express.static(root, [options]) 

The argument root represents the root directory from where the static resources are served.

You can visit express.static for more about [options] parameter. 

For example, the code written below can be used to serve images, CSS files, and JavaScript files placed in directory public:


Now, any of the files placed in the directory public can be served. Remember, we do not need to provide the name of the static file explicitly. The files are looked up relative to the static directory by Express, therefore we do not need to explicitly specify the name of the static resource. 


We also do not need to write code to serve individual static files placed in a static directory.

The express.static function can be called more than once to serve more than one static resource directories.


We can add a virtual path prefix (this path actually does exist) for files that are served by the express.static function, such as, 

app.use('/static', express.static('public'))

Now, you can load the files that are in the public directory from the /static path prefix. 

http://localhost:3000/ static/css/index.css
http://localhost:3000/ static/js/index.js
http://localhost:3000/ static/images/background.png
http://localhost:3000/ static/welcome.html

For example,

var express = require('express');
var app = express();


//Serves all the request which includes /images in the url from Images folder
app.use('/images', express.static(__dirname + '/Images'));

var server = app.listen(3000);

The rose.jpeg will be served as,