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>
转回字符串
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
arrBuffer的值为
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
发布评论