前言
在大多数介绍 Buffer 的文章中,主要是围绕数据拼接和内存分配这两方面的。比如我们使用fs模块来读取文件内容的时候,返回的就是一个 Buffer:
fs.readFile('filename', function (err, buf) {
// <Buffer 2f 2a 2a 0a 20 2a 20 53 75 ... >
});在使用net或http模块来接收网络数据时,data事件的参数也是一个 Buffer,这时我们还需要使用
Buffer.concat()来做数据拼接:
var bufs = [];
conn.on('data', function (buf) {
bufs.push(buf);
});
conn.on('end', function () {
// 接收数据结束后,拼接所有收到的 Buffer 对象
var buf = Buffer.concat(bufs);
});还可以利用
Buffer.toString()来做转换base64或十六进制字符的转换,比如:
console.log(new Buffer('hello, world!').toString('base64'));
// 转换成 base64 字符串:aGVsbG8sIHdvcmxkIQ==console.log(new Buffer('aGVsbG8sIHdvcmxkIQ==', 'base64').toString());
// 还原 base64 字符串:hello, world!
console.log(new Buffer('hello, world!').toString('hex'));
// 转换成十六进制字符串:68656c6c6f2c20776f726c6421
console.log(new Buffer('68656c6c6f2c20776f726c6421', 'hex').toString());
// 还原十六进制字符串:hello, world!
一般情况下,单个 Node.js 进程是有最大内存限制的,以下是来自官方文档中的说明:
What is the memory limit on a node process?
Currently, by default v8 has a memory limit of 512MB on 32-bit systems, and 1.4GB on 64-bit systems. The limit can be raised by setting –max_old_space_size to a maximum of ~1024 (~1 GB) (32-bit) and ~4096 (~4GB) (64-bit), but it is recommended that you split your single process into several workers if you are hitting memory limits.
由于 Buffer 对象占用的内存空间是不计算在 Node.js 进程内存空间限制上的,因此,我们也常常会使用 Buffer 来存储需要占用大量内存的数据:
// 分配一个 2G-1 字节的数据
// 单次分配内存超过此值会抛出异常 RangeError: Invalid typed array length
var buf = new Buffer(1024 * 1024 * 1024 - 1);以上便是 Buffer 的几种常见用法。然而,阅读 Buffer 的 API 文档时,我们会发现更多的是
readXXX()和
writeXXX()开头的 API,具体如下: buf.readUIntLE(offset, byteLength[, noAssert])
buf.readUIntBE(offset, byteLength[, noAssert])
buf.readIntLE(offset, byteLength[, noAssert])
buf.readIntBE(offset, byteLength[, noAssert])
buf.readUInt8(offset[, noAssert])









