Node.js Buffer用法解读

2020-06-17 06:55:11易采站长站整理

清空buffer数据最快的办法是buffer.fill(0)

buffer模块与Buffer的关系

Buffer是全局global上的一个引用,指向的其实是buffer.Buffer


const buffer = require('buffer');
console.log(buffer.Buffer === Buffer); //true

buffer模块上还有其他一些属性和方法


const buffer = require('buffer');
console.log(buffer);
{ Buffer:
{ [Function: Buffer] poolSize: 8192,
from: [Function: from],
alloc: [Function: alloc],
allocUnsafe: [Function: allocUnsafe],
allocUnsafeSlow: [Function: allocUnsafeSlow],
isBuffer: [Function: isBuffer],
compare: [Function: compare],
isEncoding: [Function: isEncoding],
concat: [Function: concat],
byteLength: [Function: byteLength],
[Symbol(node.isEncoding)]: [Function: isEncoding] },
SlowBuffer: [Function: SlowBuffer],
transcode: [Function: transcode],
INSPECT_MAX_BYTES: 50,
kMaxLength: 2147483647,
kStringMaxLength: 1073741799,
constants: { MAX_LENGTH: 2147483647, MAX_STRING_LENGTH: 1073741799 } }

上面的kMaxLength与MAX_LENGTH代表了新建buffer时内存大小的最大值,当超过限制值后就会报错

32为机器上是(2^30)-1(~1GB)

64位机器上是(2^31)-1(~2GB)

Buffer释放

我们无法手动对buffer实例进行GC,只能依靠V8来进行,我们唯一能做的就是解除对buffer实例的引用

参考资料

http://cenalulu.github.io/linux/character-encoding/
//www.jb51.net/article/31045.htm
http://edu.jb51.net/nodejs/nodejs-buffer.html