请教一个关于buffer小问题哈
发布于 10 年前 作者 chenxiaochun 4404 次浏览 最后一次编辑是 8 年前

在一篇博客中看到这样一个解释:

一旦创建或者接收了一个缓冲,你可能需要提取缓冲数据的一部分,可以通过指定起始位置来切分现有的缓冲,从而创建另外一个较小的缓冲: var buffer = new Buffer(“this is the content of my buffer”); var smallerBuffer = buffer.slice(8, 19); console.log(smallerBuffer.toString()); // -> “the content”

注意,当切分一个缓冲的时候并没有新的内存被分配或复制,新的缓冲使用父缓冲的内存,它只是父缓冲某段数据(由起始位置指定)的引用。这段话含有几个意思。

首先,如果你的程序修改了父缓冲的内容,这些修改也会影响相关的子缓冲,因为父缓冲和子缓冲是不同的JavaScript对象,因此很容易忽略这个问题,并导致一些潜在的bug。

于是乎,我就这样实际的测试了一下: var buffer = new Buffer(“this is the content of my buffer”);
var smallerBuffer = buffer.slice(0, 4); console.log(smallerBuffer.toString()); // -> “the content”

buffer[1] = ‘a’; console.log(smallerBuffer.toString());

程序运行之后的输出是: this tis 为什么第二次的输出不是tais呢,“百撕不得其姐”,忘哪位大神儿给指点一下,谢谢哈。。。

6 回复

buffer 赋值要输入整数。‘a’被转化成整数,就变成0了。

$ node

var buffer = new Buffer(“this is the content of my buffer”); undefined buffer <Buffer 74 68 69 73 20 69 73 20 74 68 65 20 63 6f 6e 74 65 6e 74 20 6f 66 20 6d 79 20 62 75 66 66 65 72> buffer[1] 104

var smallerBuffer = buffer.slice(0, 4); smallerBuffer <Buffer 74 68 69 73>

console.log(smallerBuffer.toString()); this

buffer[1] = ‘a’; ‘a’

buffer <Buffer 74 00 69 73 20 69 73 20 74 68 65 20 63 6f 6e 74 65 6e 74 20 6f 66 20 6d 79 20 62 75 66 66 65 72>

smallerBuffer <Buffer 74 00 69 73>

buffer[1] = 68 68 smallerBuffer <Buffer 74 44 69 73>

buffer[1] = 0x68 104 smallerBuffer <Buffer 74 68 69 73>

Buffer的API文档说的清楚, buffer[index] 这样子的操作,只能接受一个字节的参数。

Javascript里面’a’是由两个字节来标示的,前面一个字节是 0。

验证一下

> var buffer = new Buffer('this');
> buffer[1] = 'a';
> buffer.toString('hex')
'74006973'
> buffer.toString()
't\u0000is'
> buffer.toJSON()
[ 116, 0, 105, 115 ]
> buffer
<Buffer 74 00 69 73>

要想得到期望的输出,正确的方式是

> buffer[1] = 0x61;
> buffer.toString()
'tais'

‘a’ 与 0x61 在 js 中不是一个东西。。。明显是 C/C++ 用多了。。。

但是官方也是建议这么转换的,还说very fast。详见:http://nodejs.org/api/buffer.html#buffer_buffer

先把官方文档好好看一遍,一个一个模块看。然后再看其它的书,博客之类的。。

回到顶部