0

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?

2
  • Strange, the only thing I can think is putting data1 into a buffer includes the string terminator. Commented Feb 1, 2017 at 4:17
  • Neither of those is reading the file directly in base64? Commented Feb 1, 2017 at 5:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah I missed the from(data, encoding)... Good to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.