Buffer 类是一个全局变量。Buffer 类的实例相似于整数数组,但 Buffer 的大小是固定的、且不与 V8 共用内存。 Buffer 的大小在建立时肯定,且没法改变。javascript
console.log(Buffer.from('hello world')); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> console.log(Buffer.from([65, 66, 67, 68])); // <Buffer 41 42 43 44> const arr = new Uint8Array(2); arr[0] = 65; arr[1] = 66; const buf = Buffer.from(arr.buffer); console.log(buf.toString('utf8')); // AB arr[1] = 67; console.log(buf.toString('utf8')); // AC
使用字符/数组/数组/arrayBuffer 建立buffer。
若是使用 arrayBuffer 建立buffer,arrayBuffer 与 Buffer内存将共享。
ArrayBuffer传送门css
console.log(Buffer.alloc(5)); console.log(Buffer.alloc(5, 'abc').toString()); console.log(Buffer.alloc(5, 'abcdef').toString('utf8')); console.log(Buffer.alloc(5, '见面打声招呼', 'gb2312').toString('utf8')); // <Buffer 00 00 00 00 00> // abcab // abcde // 见�
填充内容不足的状况下重复填充。
填充内容大小超出可用内存大小将被截断;
中文按照三个字节来计算,因此上面出现了乱码;
不传入填充内容的状况下使用空字符填充Buffer,这里的空字符不是指空格字符;html
console.log(Buffer.allocUnsafe(5)); console.log(Buffer.allocUnsafe(5)); // <Buffer 60 07 04 03 01> // <Buffer 80 07 04 03 01>
等同于 node v6.0.0 以前的 new Buffer();以这种方式建立的 Buffer 的内存是未初始化的。 Buffer 的内容是未知的,可能包含已存在数据。
不推荐,若是必定要用,使用须要使用 Buffer.fill 进行填充,或者直接使用Buffer.alloc。
Buffer 模块预先分配大小为 8Kb (Buffer.poolSize)的内部 Buffer 池,用来快速分配给新 Buffer 实例。Buffer.alloc 永远不会使用内部 Buffer 池。Buffer 池空间大于一半时,Buffer.allocUnsafe 将优先使用预分配的 Buffer 池,返回一个内存地址,相似于指针概念。java
Buffer.allocUnsafeSlow();
与 Buffer.allocUnsafe 的区别是,不会使用预分配 Buffer池,而是从外部获取一块内存,生成新的 Buffer。能够避免 Buffer池 建立太多的Buffer。node
const txtPath = path.join(__dirname, './test.txt'); const content = fs.readFileSync(txtPath); // <Buffer 61 62 63 ...> console.log(content.toString('utf8')); // content
node 中文件的传输与读取以及写入操做都是有基于 Buffer 进行操做。linux
Buffer 还有各类转码,以及读取写入等操做,具体看API 这里不作过多介绍api
内容等比切割
文件读取传输操做
资源临时存储,不如js,css等静态文件
...数组
http://nodejs.cn/api/buffer.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
http://guojing.me/linux-kernel-architecture/posts/how-slab-work/post