Display local image in Node.js Express framework

Express.js is the most popular web framework for Node.js. Now, I will show you how to show an image on a web page from your local directory in Express.js with the HTML img tag.

Express already has a built-in middleware function to serve static files. The express.static is the function that I am talking about. This function is going to help us to do our task.

Now see it in an example.

First of all, include the Express module and create an object of express() function:

const express = require('express')
const app = express()

Now suppose your image file is inside a directory called “images” which is inside the directory “public”. Your image path is like you can see below:

public/images/myimg.jpg

Now, we want to display our image with the HTML img tag of an HTML file which is “index.html”. Now using the express.static function, we can set our static files path where our image located”

app.use(express.static(__dirname+'/public'));

Below is the complete Node.js JavaScript code as our example:

const express = require('express');
const app = express();
const port = 3000;

// Define the static file path
app.use(express.static(__dirname+'/public'));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
})

app.listen(port, () => console.log('The server running on Port '+port));

Now in our HTML file, we just need to use the path in our HTML img tag just like you can see below:

<img src="images/myimg.jpg">

You can see that we haven’t used the “public” directory name in the src attribute value of img tag. This is because we have already mentioned the static path using the express.static() function.

Also, read:

Now if we run our code and open it on our browser, we will able to see the image on the web page. That means we are able to display our local image using the Node Express.js framework with HTML img tag from an HTML file.

Leave a Reply

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