前言
在大多數介紹 Buffer 的文章中,主要是圍繞數據拼接和內存分配這兩方面的。比如我們使用fs模塊來讀取文件內容的時候,返回的就是一個 Buffer:
fs.readFile('filename', function (err, buf) { // <Buffer 2f 2a 2a 0a 20 2a 20 53 75 ... >});在使用net或http模塊來接收網絡數據時,data事件的參數也是一個 Buffer,這時我們還需要使用Buffer.concat()來做數據拼接:
var bufs = [];conn.on('data', function (buf) { bufs.push(buf);});conn.on('end', function () { // 接收數據結束后,拼接所有收到的 Buffer 對象 var buf = Buffer.concat(bufs);});還可以利用Buffer.toString()來做轉換base64或十六進制字符的轉換,比如:
console.log(new Buffer('hello, world!').toString('base64'));// 轉換成 base64 字符串:aGVsbG8sIHdvcmxkIQ==console.log(new Buffer('aGVsbG8sIHdvcmxkIQ==', 'base64').toString());// 還原 base64 字符串:hello, world!console.log(new Buffer('hello, world!').toString('hex'));// 轉換成十六進制字符串:68656c6c6f2c20776f726c6421console.log(new Buffer('68656c6c6f2c20776f726c6421', 'hex').toString());// 還原十六進制字符串:hello, world!一般情況下,單個 Node.js 進程是有最大內存限制的,以下是來自官方文檔中的說明:
What is the memory limit on a node process?
Currently, by default v8 has a memory limit of 512MB on 32-bit systems, and 1.4GB on 64-bit systems. The limit can be raised by setting --max_old_space_size to a maximum of ~1024 (~1 GB) (32-bit) and ~4096 (~4GB) (64-bit), but it is recommended that you split your single process into several workers if you are hitting memory limits.
由于 Buffer 對象占用的內存空間是不計算在 Node.js 進程內存空間限制上的,因此,我們也常常會使用 Buffer 來存儲需要占用大量內存的數據:
// 分配一個 2G-1 字節的數據// 單次分配內存超過此值會拋出異常 RangeError: Invalid typed array lengthvar buf = new Buffer(1024 * 1024 * 1024 - 1);
以上便是 Buffer 的幾種常見用法。然而,閱讀 Buffer 的 API 文檔時,我們會發現更多的是readXXX()和writeXXX()開頭的 API,具體如下:
新聞熱點
疑難解答
圖片精選