Node.js, 使用 Buffers 操作,编码、解码,二进制数据。

JavaScript 是很擅长处理字符串的,但是它最初是为增强浏览器功能而生,主要是去处理HTML文档,虽然它也有位运算,可是它处理二进制的能力很弱。

JavaScript 没有 byte 类型。(它只是有数字或结构化类型,甚至是字节数组: 它只是有字符串。)


Node.js 平台 使用 JavaScript 编程,为了使二进制处理任务容易, Node.js 包含了一个Buffers 类。


一、buffer 的创建三种方法

var buf 1= new Buffer('Hello World!');
var buf 2= new Buffer('8b76fde713ce', 'base64'); //ascii, utf8,base64
var buf 3= new Buffer(1024); // creating a 1024 byte buffer,,记住,它将包含随机字节,而不是零!!


二、获取、更改 buffer 对象中的字节。

var buf = new Buffer('my buffer content');
// accessing the 10th position of buf
console.log(buf[10]); // -> 99


var buf = new Buffer(1024);
console.log(buf[100]); // -> 5 (some random number)


******************************************************************************************

NOTE In certain cases, some buffer operations will not yield an error. For
instance:
➤ If you set any position of the buffer to a number greater than 255, that
position will be assigned the 256 modulo value.
➤ If you assign the number 256 to a buffer position, you will actually be
assigning the value 0.
➤ If you assign a fractional number like 100.7 to a buffer position, the buffer
position will store the integer part — 100 in this case.
➤ If you try to assign a position that is out of bounds, the assignment will fail
and the buffer will remain unaltered.

******************************************************************************************

当你创建或接收到一个buffer,你可能想要提取其中一部分数据。你可以 slice 一个 buffer 来创建另一个较小的 buffer ,指定起点和终点的位置,代码如下:


var buffer = new Buffer("this is the content of my buffer");
var smallerBuffer = buffer.slice(8, 19);
console.log(smallerBuffer.toString()); // -> "the content"



重要: 当你 slice 一个buffer  并没有新的内存分配,与复制!

所以,

1>:当你修改 切出来的buffer时,父buffer 也被修改,反之亦然。

2>: 以这种方式创建的小 buffer ,父 buffer 必须在 "手术" 后保存,不会被垃圾回收器回收,容易产生内存泄漏。


更安全的方式,复制:


var buffer1 = new Buffer("this is the content of my buffer");
var buffer2 = new Buffer(11);
var targetStart = 0;
var sourceStart = 8;
var sourceEnd = 19;
buffer1.copy(buffer2, targetStart, sourceStart, sourceEnd);
console.log(buffer2.toString()); // -> "the content"



编码一个buffer


var str = buf.toString();//默认使用utf8编码var utf8String = 'my string';
var buf = new Buffer(utf8String);
var base64String = buf.toString('base64')






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值