CNode

关于Buffer的write方法的疑惑

问答
Ssxycjj发布于10 年前最后回复10 年前2 回复4061 浏览0 收藏

var buf = new Buffer(10);

// 每次写入的内容不一致 buf.write('zhangsan');

console.log(buf); console.log(buf.length); console.log(buf.toString()); 屏幕快照 2016-09-07 下午3.58.57.png

这里每次输出的结果不一样,为什么?

查看回复

回复 (2)

N
njaulj#1·10 年前

来看看官方文档对于 Buffer这块的说明 传送门

new Buffer(size)# size Allocates a new Buffer of size bytes. The size must be less than or equal to the value of require('buffer').kMaxLength (on 64-bit architectures, kMaxLength is (2^31)-1). Otherwise, a RangeError is thrown. If a size less than 0 is specified, a zero-length Buffer will be created. Unlike ArrayBuffers, the underlying memory for Buffer instances created in this way is not initialized. The contents of a newly created Buffer are unknown and could contain sensitive data. Use buf.fill(0) to initialize a Buffer to zeroes.

const buf = new Buffer(5);
console.log(buf);
  // <Buffer 78 e0 82 02 01>
  // (octets will be different, every time)
buf.fill(0);
console.log(buf);
  // <Buffer 00 00 00 00 00>
N
ncuzp#2·10 年前

其实你这个buf里面的后两个字节是不确定的,因为zhangsan只占用8个字节,而你分配了十个字节,另外两个字节由于你没有初始化置0,所以它的值是未知的,可能会有其他程序对这两个字节所占用内存进行读写

参与回复
登录后即可参与回复。登录