Risan Bagja

Journal of a passionate coder

Express Responds with Base64 Encoded Image

I want to create an endpoint that will respond with a 1x1 pixel PNG file. Instead of using the sendFile method, I choose to use the base64 encoded representation since the file size is super small. This way I can avoid accessing the file system entirely.

Hereโ€™s the gist:

const express = require("express");

const app = express();

app.get("/test.png", (req, res) => {
  // A 1x1 pixel red colored PNG file.
  const img = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==", "base64");


Note that when you pass a Buffer, the content-type header will be set to application/octet-stream.