nodejs系列笔记01---Buffer
纯JavaScript无法处理二进制数据,buffer就是用来处理二进制数据的
原始数据保存在buffer实例中,一个buffer实例类似于数组。buffer的大小在建立时指定的不可更改。
buffer是一个全局类,不需要使用require来引入。
在buffer和JavaScript string转换时,需要指定编码方式
Class:Buffer
new Buffer(array)
使用字节数组创建一个buffer实例
已弃用 现使用Buffer.from(array)替代
var buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]);
// ['b','u','f','f','e','r']
new Buffer (buffer)
复制一个buffer实例到另一个新创建的buffer中
已弃用 现使用Buffer.from(buffer)替代
const buf1 = new Buffer('buffer');
const buf2 = new Buffer(buf1);
buf1[0] = 0x61;//改变buf1'buffer'第一个字符的值
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 复制过去的新buffer没有改变
new Buffer(size)
已弃用 现使用Buffer.alloc(size[, fill[, encoding]]) 替代
创建一个大小是size的新的buffer
const buf = new Buffer(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// 值不确定
buf.fill(0);//用0填充
console.log(buf);
// <Buffer 00 00 00 00 00>
new Buffer(str[,encoding])
创建一个新的buffer,值为str,编码为encoding
已弃用 现使用Buffer.alloc(size[, fill[, encoding]]) 替代
const buf1 = new Buffer('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
Class Method:Buffer.alloc(size[, fill[, encoding]])
- size
- fill
Default: undefined - encoding
Default: utf8
创建一个size大小的buffer,当fill没有指定时,默认为00
size必须小于等于require('buffer').kMaxLength的值,否则会抛出RangeError错误。
如果fill被指定,将会自动调用buf.fill(fill)
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// <Buffer 61 61 61 61 61>
如果fill和encoding都被指定,将会自动调用buf.fill(fill,encoding)
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
Buffer.alloc(size)比Buffer.allocUnsafe(size)慢一些,但创建的数据不会包含敏感数据
当size不是数字是会抛出TypeError错误
Class Method: Buffer.allocUnsafe(size)
- size
创建一个size大小的buffer,并且值不确定。为了避免包含敏感数据,请使用buf.fill(0)初始化为0
size必须小于等于require('buffer').kMaxLength的值,否则会抛出RangeError错误。
const buf = Buffer.allocUnsafe(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>
Note that the Buffer module pre-allocates an internal Buffer instance of size Buffer.poolSize that is used as a pool for the fast allocation of new Buffer instances created using Buffer.allocUnsafe(size) (and the deprecated new Buffer(size) constructor) only when size is less than or equal to Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two). The default value of Buffer.poolSize is 8192 but can be modified.
当有快速的buffer分配时,如果Buffer.allocUnsafe(size)的size小于等于Buffer.poolSize的一半时,Buffer模块会创建一个内部缓冲池。这个缓冲池的默认大小Buffer.poolSize是8192,但他是可修改的
Use of this pre-allocated internal memory pool is a key difference between calling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill). Specifically, Buffer.alloc(size, fill) will never use the internal Buffer pool, while Buffer.allocUnsafe(size).fill(fill) will use the internal Buffer pool if size is less than or equal to half Buffer.poolSize. The difference is subtle but can be important when an application requires the additional performance that Buffer.allocUnsafe(size) provides.
使用Buffer.alloc(size,fill)和Buffer.allocUnsafe(size).fill(fill)有一些细微的差别。Buffer.alloc(size,fill)不会使用内部的缓冲池,而Buffer.allocUnsafe(size).fill(fill)在size小于等于Buffer.poolSize的一半时会使用内部缓冲池。这点不同虽然很细微,但如果一个应用需要Buffer.allocUnsafe(size)提供的这一点额外性能的话,它还是很关键的.
Class Method: Buffer.allocUnsafeSlow(size)
- size
Allocates a new non-zero-filled and non-pooled 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. A zero-length Buffer will be created if a size less than or equal to 0 is specified.
The underlying memory for Buffer instances created in this way is not initialized. The contents of the newly created Buffer are unknown and may contain sensitive data. Use buf.fill(0) to initialize such Buffer instances to zeroes.
When using Buffer.allocUnsafe() to allocate new Buffer instances, allocations under 4KB are, by default, sliced from a single pre-allocated Buffer. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many Persistent objects.
However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() then copy out the relevant bits.
// need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
const data = socket.read();
// allocate for retained data
const sb = Buffer.allocUnsafeSlow(10);
// copy the data into the new allocation
data.copy(sb, 0, 0, 10);
store.push(sb);
});
Use of Buffer.allocUnsafeSlow() should be used only as a last resort after a developer has observed undue memory retention in their applications.
Class Method: Buffer.byteLength(string[, encoding])
- string
| | | | - encoding
Default: 'utf8' - Return:
将会返回这个字符串真实byte长度。这个和String.prototype.length是不一样的,因为那个方法返回这个字符串中有几个字符的数量。
const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// ½ + ¼ = ¾: 9 characters, 12 bytes
Class Method: Buffer.compare(buf1, buf2)
- buf1
- buf2
- Return:
返回一个数字,表示 buf 在 otherBuffer 之前(<0),之后(>0)或相同(==0)。这个方法和buf1.compare(buf2)相同。
const arr = [Buffer.from('1234'), Buffer.from('0123')];
arr.sort(Buffer.compare);
Class Method: Buffer.concat(list[, totalLength])
- list
List of Buffer objects to concat - totalLength
list中buffer的长度而不是个数 - Return:
把list中的全部buffer连接在一起后返回这个新的buffer3
如果list中没有buffer或者total length为0,将返回一个长度为0的buffer
如果没有提供totalLength的值,将会自动计算list中buffer的长度,但是直接给出会更快。
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
console.log(bufA.length);
// 42
// <Buffer 00 00 00 00 ...>
// 42
Class Method: Buffer.from(array)
- array
使用array里的字节创建一个新的buffer
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
// creates a new Buffer containing ASCII bytes
// ['b','u','f','f','e','r']
如果array不是Array 抛出TypeArray错误
Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
- arrayBuffer
一个 TypedArray的buffer属性(.buffer)或者一个new ArrayBuffer()
When passed a reference to the .buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray.
当传递一个TypedArray实例的.buffer属性时,新创建的buffer会和这个实例共享内存
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// changing the TypedArray changes the Buffer also
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
当 arrayBuffer不是TypedArray类型是抛出TypeError错误
Class Method: Buffer.from(buffer)
- buffer
复制这个buffer参数到一个新的buffer实例中
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 'buffer' (copy is not changed)
当buffer不是Buffer类型时抛出TypeError错误
Class Method: Buffer.from(str[, encoding])
- str
String to encode. - encoding
Encoding to use, Default: 'utf8'
创建一个包含给出的str的buffer实例,如果给定了encoding参数,将转换为这个参数,如果没有给定,默认为utf-8。
const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
如果str不是String类型将抛出TypeError错误
Class Method: Buffer.isBuffer(obj)
- obj

浙公网安备 33010602011771号