Create a Data URI String with Node.js

Turning an image into a data URI string with Node.js involves a few steps but can be solved pretty easily.

To learn how let's create a utility function that will read a file with fs, then convert its content to Base64, and prepend the appropriate MIME type to format it as a Data URI:

const fs = require('fs');
const path = require('path');

// Function to convert image to Data URI
const imageToDataURI = (filePath) => {
  // Determine the MIME type from the file extension
  const mimeType = 'image/' + path.extname(filePath).slice(1);

  // Read the file synchronously
  const imageData = fs.readFileSync(filePath);

  // Convert the image data to a Base64-encoded string
  const base64Image = Buffer.from(imageData).toString('base64');

  // Format the Data URI string
  const dataUri = `data:${mimeType};base64,${base64Image}`;
  
  return dataUri;
};

// Example usage
const filePath = 'path/to/your/image.png'; // Update this path to your image file
const dataUri = imageToDataURI(filePath);
console.log(dataUri);

So wtf is happening?

  • Determine MIME Type: The MIME type is inferred from the file extension using the path.extname method. This approach eliminates the need for manual extension checks, streamlining the process.

  • Read File Synchronously: The fs.readFileSync method reads the file's contents. I think using asynchronous methods (fs.readFile) in production might be a better option to prevent blocking.

  • Convert to Base64: The Buffer.from() method creates a buffer from the image data, which is then converted to a Base64 string using toString('base64').

  • Format Data URI: Finally, the Base64-encoded image data is concatenated with the MIME type to form the Data URI string.

JavaScriptNodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.