如何解决NodeJS - 如何在使用 JSON.parse(JSON.stringify()) 后从缓冲区中检索原始数据
我正在使用 crypto
库发送一个 POST 请求来更新一些数据,出于某种原因,我好像使用了 JSON.parse(JSON.stringify(myBufferData))
到一个 Buffer
数据。我想恢复原始数据。
你如何复制我的情况:
var buf = Buffer.from('abc');
var parsedBuf = JSON.parse(JSON.stringify(buf)); -> I faced with this result at some point.
buf.toString() -> Give the expected result ('abc').
parsedBuf.toString() -> Doesn't retrieve original data ('[object Object]').
如何从 parsedBuf
中检索原始数据?
解决方法
解决方案
使用 Buffer(parsedBuf).toString()
而不是 parsedBuf.toString()
来检索原始数据。
说明
检查 Buffer docs,我发现它的 toString
方法不是 Javascript 的内置方法。您可以通过调用 buf.[method].toString()
随时随地查看其来源。在这种情况下:
-
buf.toString.toString()
-
JSON.parse(JSON.stringify(buf)).toString.toString()
所以它以某种方式向我展示了他们的源代码:
// Buffer's toString method
function () {
let result;
if (arguments.length === 0) {
result = this.utf8Slice(0,this.length);
} else {
result = slowToString.apply(this,arguments);
}
if (result === undefined)
throw new Error('"toString()" failed');
return result;
}
// Javascript's built-in
function toString() { [native code] } // I haven't sought to find it out
事实证明,每当您执行 JSON.parse(JSON.stringify(buf))
时,您实际上都是在将 Buffer 转换为 Javascript 对象。例如:
{ type: 'Buffer',data: [ 61,62,63] }
。
所以它上面的另一个 toString()
将运行 native JS 函数(不是 Buffer 的),它默认返回 [object Object]
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。