To advertise with us contact on Whatsapp: +923041280395 For guest post email at: itsaareez1@gmail.com

Static Files in Express JS

Static Files in Express JS

Express JS does not allow to serve static files likes images, videos etc. Static files are downloaded by clients from server. However, if we have to serve static files, we will have to enable middleware dedicated for this purpose. To do this, first of all we will create a folder or directory named public in our project directory then add the following line of code in our index.js.

//use middleware to serve static files
app.use(express.static('public'));

The above code can also be used to create a virtual path along with setting public directory for project. To add virtual path, you can update the code as below. However, this is optional.

//use middleware to serve static files
app.use('/static', express.static('public'));

Now root route will be set to public directory for static files. To confirm it, load a picture in public directory.

doctype html 
html
    head
        //this is title
        title Welcome!
    body
        img(src="/bch.png", alt="Best Cyber Hacks")
        include ./menu.pug
        //checks if user variable is set
        if (user)
            //prints name of user
            h2 Hello Mr. #{user.firstname} #{user.lastname}
        else
            //if user is not set, prints aplogize
            h3 Aplogize, you are not logged in!
        include ./footer.pug

If you have created virtual path at /static, then use the code below for Pug.

doctype html 
html
    head
        //this is title
        title Welcome!
    body
        img(src="/static/bch.png", alt="Best Cyber Hacks")
        include ./menu.pug
        //checks if user variable is set
        if (user)
            //prints name of user
            h2 Hello Mr. #{user.firstname} #{user.lastname}
        else
            //if user is not set, prints aplogize
            h3 Aplogize, you are not logged in!
        include ./footer.pug

You will see the following output after accessing http://localhost:3000

output after adding static files in express js.png

You can also define multiple static directories which will make it easy to manage complex projects. For example, big projects have large number of different assets like CSS, JS, images, files etc. For managing all of them in different directories, we will create separate directories named css, js, images and files in project directory. Update index.js by adding the following lines of codes.

//use middleware to serve static files
app.use('/static', express.static('public'));
app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use('/files', express.static('files'));
app.use('/images', express.static('images'));

Leave a Reply

Your email address will not be published. Required fields are marked *