Sometimes, we want to decode base64 to hexadecimal string with JavaScript and Node.js.
In this article, we’ll look at how to decode base64 to hexadecimal string with JavaScript and Node.js.
How to decode base64 to hexadecimal string with JavaScript and Node.js?
To decode base64 to hexadecimal string with JavaScript and Node.js, we can use the Buffer.from
method to convert the base64 string to a buffer.
Then we can call the buffer’s toString
method with 'hex'
to convert it to a hex string.
For instance, we write:
const rawData = 'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
const buffer = Buffer.from(rawData, 'base64');
const bufString = buffer.toString('hex');
console.log(bufString)
to call Buffer.from
with the rawData
base64 string and 'base64'
to convert the rawData
base64 string to a buffer.
Then we call buffer.toString
with 'hex'
to convert the buffer to a hex string.
As a result, we get that bufString
is '75ab5a8a66a07bfa6781b6ac7bae22541391c3428682800000035252111480000001400000014201800000235bc9b940000007125110550235d8fe3fffcff0dfc1880170c804a1340c7c609633410003bd4d72f4638387c0000000125153912b909820'
.
Conclusion
To decode base64 to hexadecimal string with JavaScript and Node.js, we can use the Buffer.from
method to convert the base64 string to a buffer.
Then we can call the buffer’s toString
method with 'hex'
to convert it to a hex string.