nodejs 里字符串同Buffer之间的互转
1.string转buffer
var str = 'hello,world'; var buffer = Buffer.from(str)
buffer的值为
<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>
转回字符串
buffer.toString()
hello,world
2.使用 Uint8Array
var array = new Uint8Array(new ArrayBuffer(str.length)); for (var i = 0, il = str.length; i < il; i++) { var value = str.charCodeAt(i); array[i] = value > 0xFF ? 0x20 : value; } var arrBuffer=array.buffer
ArrayBuffer {
[Uint8Contents]: <68 65 6c 6c 6f 2c 77 6f 72 6c 64>,
byteLength: 11
}
转成buffer
Buffer.from(array.buffer)
转成字符串
(Buffer.from(array.buffer)).toString()
<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>
(Buffer.from(array.buffer)).toString()
hello,world