简体   繁体   English

使用 Buffer.alloc 在 nodejs 中进行 base64 转换的问题

[英]Problem with base64 conversion in nodejs using Buffer.alloc

I'm trying to convert some base64 conversion code that used to use the insecure Buffer constructor to use the Buffer.alloc method instead, but the conversion is behaving strangely.我正在尝试转换一些 base64 转换代码,这些转换代码曾经使用不安全的 Buffer 构造函数来使用 Buffer.alloc 方法,但是转换的行为很奇怪。 Here is my code:这是我的代码:

let originalText = JSON.stringify({city: "New York", date: "2020/05/12"});
console.log("DATA:           " + originalText)

let base64Text = Buffer.alloc(originalText.length, originalText, "binary").toString('base64');
console.log("Base64 version: " + base64Text);

let loadedBuffer = Buffer.alloc(base64Text.length, base64Text, 'base64');

const reconstitutedData  = loadedBuffer.toString();
console.log("Result:         " + reconstitutedData);

And here is the output:这是 output:

DATA:           {"city":"New York","date":"2020/05/12"}
Base64 version: eyJjaXR5IjoiTmV3IFlvcmsiLCJkYXRlIjoiMjAyMC8wNS8xMiJ9
Result:         {"city":"New York","date":"2020/05/12"}{"city":"New

The conversion is correct except for the repeated bit on the end.转换是正确的,除了最后的重复位。 Obviously the length of the base64 string is not the right length to use here, but this makes no sense because it doesn't seem like there is a way to know the length of the original string.显然 base64 字符串的长度不是在这里使用的正确长度,但这没有意义,因为似乎没有办法知道原始字符串的长度。 Maybe I'm using the API wrong?也许我使用的 API 错了?

Buffer.alloc ( doc ) is not for what you want to achieve. Buffer.alloc ( doc ) 不适合您想要实现的目标。 The second argument of Buffer.alloc is to fill the buffer entirey with that value, repeting if neccesary. Buffer.alloc的第二个参数是用该值完全填充缓冲区,必要时重复。 Is usually used to create a zero filled buffer, like so:通常用于创建一个零填充缓冲区,如下所示:

// 0 is the default value, so is not needed actually. Set for demo purposes.
let zerobuf = Buffer.alloc(1000, 0);

In this case, what you need is Buffer.from ( doc ):在这种情况下,您需要的是Buffer.from ( doc ):

let base64Text = Buffer.from(str).toString("base64");
let reconstitutedData = Buffer.from(base64Text, "base64").toString();

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

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