node.js - Nodejs Buffer.from 返回无效值
问题描述
Buffer.from(' ???', 'base64')
此代码返回一个空缓冲区而不是引发错误,这是预期的行为。在nodejs中验证编码数据的有效性并对其进行解码的正确方法是什么?
解决方案
如果给定字符串中的字符不是指定编码的一部分,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 在评论中所建议的那样。
推荐阅读
- html - 父元素布局wrt旋转元素的边界框
- rstudio - Rstudio:如何在分布上拟合包含负数和非负数的数据集(例如:对数正态)?
- scala - 在 Scala 中处理多个并发流的惯用方法
- javascript - 在整个文档维护案例中将一个特定单词更改为另一个单词
- php - Woocommerce 中的自定义结帐选择字段更改动态运输方式
- debugging - 如何在批处理模式下执行 gdb 断点命令?
- angularjs - 不确定如何创建良好的 redux 行为
- ng-build - Angular 2 Cli 应用程序 404 硬刷新时出错
- r - 按组计算标准偏差,不包括 R 中的当前观察值
- java - 没有循环或递归或乘法的前 N 个数字的总和