首页 > 解决方案 > Nodejs Buffer.from 返回无效值

问题描述

Buffer.from(' ???', 'base64')

此代码返回一个空缓冲区而不是引发错误,这是预期的行为。在nodejs中验证编码数据的有效性并对其进行解码的正确方法是什么?

标签: node.jsencodingbase64

解决方案


如果给定字符串中的字符不是指定编码的一部分,nodejs 12.16 文档中似乎没有关于引发错误的任何内容。

事实上,一个小实验似乎表明,Buffer.from()简单地忽略这些不属于编码的字符。

try{
    const str1 = "ai?73";
    const str2 = "ai73";
    const str3 = "??a?i73??";
    const encoded1 = Buffer.from(str1,'base64').toString('base64');
    const encoded2 = Buffer.from(str2,'base64').toString('base64');
    const encoded3 = Buffer.from(str3,'base64').toString('base64');
    console.log(`On base64 encoding ${str1}: ${encoded1}`);
    console.log(`On base64 encoding ${str2}: ${encoded2}`);
    console.log(`On base64 encoding ${str3}: ${encoded3}`);
}catch(e){
    console.error(`ERROR:`,e);
}

它产生以下输出:

On base64 encoding ai?73: ai73
On base64 encoding ai73: ai73
On base64 encoding ??a?i73??: ai73

所以,你最好的选择是使用像 is-base64 这样的包,正如用户 dajnz 在评论中所建议的那样。

https://www.npmjs.com/package/is-base64


推荐阅读