API to return image in Node JS

In this article, we will show you, how you can return an image from the response of an API in Node JS.

Video tutorial:

First, I will create an image tag and set the “src” attribute as the path of the API. I also send “adnan” as an argument so the server will know which image to fetch.

<img src="/showImage/adnan" />

Then I am going to create a GET API in Node JS.

const fs = require("fs")

app.get("/showImage/:name", async function (request, result) {
  const name = request.params.name
  const image = await db.collection("images")
    .findOne({
      name: name
    })
  if (image == null) {
    let defaultImage = await fs.readFileSync("public/default.jpg")
    defaultImage = Buffer.from(defaultImage, "base64")
    
    result.writeHead(200, {
      "Content-Type": "image/jpg",
      "Content-Length": defaultImage.length
    })
    result.end(defaultImage)
    return
  }
  
  const imageContent = await fs.readFileSync(image.path)
  
  result.writeHead(200, {
    "Content-Type": "image/jpg",
    "Content-Length": imageContent.length
  })
  result.end(imageContent)
  return
})

If you run the code now, you will be able to see the image.