In this tutorial we will see how express serves static files. Express module has a middleware function static() which instructs express to treat a folder as static. Let us take a look at the below example.

Example – Express Serve Static File

Before we begin, create a folder at the project root and name it “files”. Now create another folder and name it “images”. After folder creation, place an image inside the images folder. Your folder structure should look like below.

express static file image

Now create a javascript file and place the below code. Run the code and invoke url http://localhost:8080/images/<yourimagename>.png. You will see the image served to the browser.

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

Make a note that the folder “files” is not part of the url.

Express Serve Static File