在一篇博客中看到这样一个解释:
一旦创建或者接收了一个缓冲,你可能需要提取缓冲数据的一部分,可以通过指定起始位置来切分现有的缓冲,从而创建另外一个较小的缓冲: 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呢,“百撕不得其姐”,忘哪位大神儿给指点一下,谢谢哈。。。