Nodejs Buffer.from returns 无效值
Nodejs Buffer.from returns invalid value
Buffer.from(' ???', 'base64')
此代码 returns 一个空缓冲区,而不是抛出错误,这是预期的行为。在nodejs中验证编码数据有效性和解码的正确方法是什么?
如果给定字符串中的字符不是指定编码的一部分,nodejs 12.16 docs 中似乎没有关于抛出错误的内容。
事实上,一个小实验似乎表明 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 在评论中所建议的那样。
Buffer.from(' ???', 'base64')
此代码 returns 一个空缓冲区,而不是抛出错误,这是预期的行为。在nodejs中验证编码数据有效性和解码的正确方法是什么?
如果给定字符串中的字符不是指定编码的一部分,nodejs 12.16 docs 中似乎没有关于抛出错误的内容。
事实上,一个小实验似乎表明 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 在评论中所建议的那样。