Example serving static files in express

Serving Static Files

Express provides a built-in middleware express.static to serve static files, such as images, CSS, JavaScript, etc.

You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this −

app.use(express.static('public'));

We will keep a few images in public/images sub-directory as follows −

node_modules

express_static_files.js

public/

public/images

public/images/thor.jpg

Example:

 

var express = require('express');

var app = express();

app.use(express.static('public'));

 

app.get('/', function (req, res) {

   res.send('Hello World');

});

var server = app.listen(8080, function () {

   var host = server.address().address;

   var port = server.address().port;

 

   console.log("Example app listening at http://%s:%s", host, port);

 

});

 

Run :

 

C:\Nodejs>node express_static_files.js

Server listening at http://:::8080

 

Go browser go http://localhost:8080/images/thor.jpg