Steven
Steven

Reputation: 13

Javascript buffer inconsistency when converting between binary and base64

I need to convert a png between binary and base64 due to communication with the server. However, when I use buffer there is inconsistency between directly reading the file in base64 versus reading the file in binary then converting to base64.

const fs = require('fs');
var data1 = Buffer.from(fs.readFileSync('test.png')).toString();
data1 = Buffer.from(data1).toString('base64');
var data2 = Buffer.from(fs.readFileSync('test.png')).toString('base64');
data1 == data2; //false

What could be causing the discrepancy?

Upvotes: 0

Views: 103

Answers (1)

Steven
Steven

Reputation: 13

I think I have found the problem. As someone else mentioned, the default encoding is utf-8. However, it seems utf-8 causes some information loss so it's impossible to convert it back to base64. Therefore, one only has to specify the encoding for this to work.

const fs = require('fs');
var data1 = Buffer.from(fs.readFileSync('test.png')).toString('binary');
data1 = Buffer.from(data1,'binary').toString('base64');
var data2 = Buffer.from(fs.readFileSync('test.png')).toString('base64');
data1 == data2; //true

However, I'm curious why utf-8 would causes this problem and it would be great if someone would give me a hand.

Upvotes: 1

Related Questions