简体   繁体   English

在二进制和base64之间转换时Javascript缓冲区不一致

[英]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. 由于与服务器之间的通信,我需要在二进制和base64之间转换png。 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. 但是,当我使用缓冲区时,直接读取base64中的文件与读取二进制文件然后转换为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? 是什么导致差异?

I think I have found the problem. 我想我已经找到问题了。 As someone else mentioned, the default encoding is utf-8. 如其他人所述,默认编码为utf-8。 However, it seems utf-8 causes some information loss so it's impossible to convert it back to base64. 但是,utf-8似乎会导致某些信息丢失,因此无法将其转换回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. 但是,我很好奇为什么utf-8会导致此问题,如果有人帮我忙,那会很棒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM