[英]node.js buffer strange behavior
I'm trying to duplicate a buffer with slice of its arraybuffer, but the result buffer contains wrong value. 我正在尝试使用其arraybuffer的slice复制一个缓冲区,但是结果缓冲区包含错误的值。 Here is the example:
这是示例:
var sourceBuf = new Buffer(1);
sourceBuf.writeUInt8(1, 0);
var slice = sourceBuf.buffer.slice(0,1);
var resultBuf = new Buffer(slice);
console.log(resultBuf.readUInt8(0));
outputs 118
输出
118
In case of TypedArray all works as I at first expected: 在TypedArray的情况下,所有功能都如我最初预期的那样:
var sourceBuf = new Uint8Array(1);
sourceBuf[0] = 1;
var slice = sourceBuf.buffer.slice(0,1);
var resultBuf = new Uint8Array(slice);
console.log(resultBuf[0]);
outputs 1
输出
1
So for now I want to know what causes such "different behavior". 因此,现在我想知道是什么原因导致了这种“不同行为”。
You seem to access the internal buffer and read the value. 您似乎正在访问内部缓冲区并读取该值。 Try accessing the value like this:
尝试像这样访问值:
var sourceBuf = new Buffer(1);
sourceBuf.writeUInt8(1, 0);
var slice = sourceBuf.slice(0,1); // Changed this line
var resultBuf = new Buffer(slice);
console.log(resultBuf.readUInt8(0));
There are two possible cases on how the error gets generated: 关于错误如何产生的两种可能的情况:
buffer
-property is uninitialized internally buffer
属性在内部未初始化 In either way, accessing that property seemed to be the error. 无论哪种方式,访问该属性似乎都是错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.