var buf = new Buffer(10);
// 每次写入的内容不一致 buf.write(‘zhangsan’);
console.log(buf); console.log(buf.length); console.log(buf.toString());
这里每次输出的结果不一样,为什么?
来看看官方文档对于 Buffer这块的说明 传送门
new Buffer(size)# size <Number> 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
andcould contain sensitive data
. Usebuf.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>
其实你这个buf里面的后两个字节是不确定的,因为zhangsan只占用8个字节,而你分配了十个字节,另外两个字节由于你没有初始化置0,所以它的值是未知的,可能会有其他程序对这两个字节所占用内存进行读写