[英]How to convert a buffer in an array in Nodejs?
如何轉換數組中的緩沖區?
緩沖區(十六進制值):
myBuffer = <Buffer 48 65 6c 6c 6F >
我想要一個像這樣的變量類型數組:
myArray = [48, 65, 6c, 6c, 6F] // Hex values
or
myArray = [72, 101, 108, 108, 111] // Decimal values
重要提示:我不想使用for
循環逐字節遍歷緩沖區。 我想知道是否有將 Buffer 轉換為 Array 的本機方法。
看起來您是在指Node.js緩沖區。 在這種情況下,您可以簡單地執行以下操作:
var buf = new Buffer([72,101,108,108,111]) //<Buffer 48 65 6c 6c 6f>
var arr = Array.prototype.slice.call(buf) //[72,101,108,108,111]
如果您在談論數組緩沖區,請嘗試以下方法:
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
如果您在談論nodejs緩沖區對象,請嘗試以下操作:
let bufferOne = Buffer.from('This is a buffer example.');
console.log(bufferOne);
// Output: <Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>
let json = JSON.stringify(bufferOne);
console.log(json);
// Output: {"type":"Buffer","data": [84,104,105,115,32,105,115,32,97,32,98,117,102,102,101,114,32,101,120,97,109,112,108,101,46]}
json = JSON.parse(json);
json.data.forEach(e=> console.log(e.toString(16)));
// Output: 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e
在 ES6 中,這也可以工作:
const buffer = new Buffer([72,101,108,108,111])
const arr = [...buffer] //[72,101,108,108,111]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.