InsightsTopicsContact
Eckher
Your guide to what's next.
Home › Eckher Insights › Generating data URLs in JavaScript
Mar 1, 2020

Generating data URLs in JavaScript

How to generate data URLs in JavaScript?

All data URLs begin with data:, followed by the optional media type, encoding, and the data itself.

Below are examples of data URLs (data URIs) and how to generate them.

text/plain data, UTF-8 encoding

const data = 'Hello World!'
console.log(`data:text/plain;utf8,${encodeURIComponent(data)}`)

text/plain data, base64 encoding

const data = 'Hello World!'
console.log(`data:text/plain;base64,${toa(data)}`) // Browser
console.log(`data:text/plain;base64,${Buffer.from(data).toString('base64')}`) // Node.js

text/html data, base64 encoding

const data = '<b>Hello World!</b>'
console.log(`data:text/html;base64,${btoa(data)}`) // Browser
console.log(`data:text/html;base64,${Buffer.from(data).toString('base64')}`) // Node.js

image/svg+xml data, base64 encoding

const data =
    `<?xml version="1.0"?>
    <svg xmlns="http://www.w3.org/2000/svg" height="100" width="100">
        <circle cx="50" cy="50" r="20" fill="yellow" />
    </svg>`
console.log(`data:image/svg+xml;base64,${btoa(data)}`) // Browser
console.log(`data:image/svg+xml;base64,${Buffer.from(data).toString('base64')}`) // Node.js
Cover
See also
Using language codes
Official language codes used on the web.
Parsing XML in JavaScript
How to parse XML in JavaScript?
Iterating over Map in JavaScript
Gotchas with iterating over a Map object in JavaScript.
Asynchronous iteration in JavaScript
Gotchas with asynchronous iteration in JavaScript.
Creating a JavaScript library with webpack
How to bundle a JavaScript library with webpack?
Creating a playlist in React
How to create a playlist in React?
Server-side rendering with code splitting
How to implement server-side rendering with code splitting?
What does a senior developer do?
The difference between an intermediate and senior developer.
Eckher
Your guide to what's next.
Copyright © 2021 Eckher. Various trademarks held by their respective owners.