一、Node.js Buffer簡介
Node.js的Buffer是用來處理二進位數據的類,它可以直接操作底層的二進位數據,也可以將二進位數據轉換成字元串格式。在Node.js中,Buffer是一個全局對象,無需使用require語句引入,即可在任何地方訪問。
二、Node.js Buffer使用場景
Node.js Buffer可用於處理網路、文件、壓縮、加密等數據流,包括:
1、文件流:文件操作時,讀取的內容默認為Buffer格式。
2、網路流:在發送網路請求時,請求體中的數據會被轉化為Buffer格式,並在接收網路響應時將收到的數據以Buffer形式返回。
3、加密:加密的輸入輸出均為Buffer格式。
4、字元串轉二進位數據:例如將字元串轉換成UTF-8編碼的二進位數據。
三、創建Buffer實例
可以使用Buffer.alloc(size[, fill[, encoding]])、Buffer.allocUnsafe(size)、Buffer.from(array)、Buffer.from(string[, encoding])等方法創建Buffer實例。
1、使用Buffer.alloc(size[, fill[, encoding]])方法創建Buffer實例
const buf1 = Buffer.alloc(10); // 創建長度為10,用0x00填充的Buffer實例
const buf2 = Buffer.alloc(10, 1); // 創建長度為10,用0x01填充的Buffer實例
const buf3 = Buffer.alloc(10, 'a', 'utf8'); // 創建長度為10,用'a'填充的Buffer實例
2、使用Buffer.allocUnsafe(size)方法創建Buffer實例
const buf = Buffer.allocUnsafe(10); // 創建長度為10,只是預分配了內存空間,是未初始化的Buffer實例
buf.fill(0); // 初始化內存為0
3、使用Buffer.from(array)方法創建Buffer實例
const buf = Buffer.from([0x01, 0x02, 0x03]); // 創建Buffer實例,長度為3,內容為0x01, 0x02, 0x03
4、使用Buffer.from(string[, encoding])方法創建Buffer實例
const buf = Buffer.from('hello world', 'utf8'); // 創建Buffer實例,長度為11(utf8編碼),內容為'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'
四、Node.js Buffer常用方法
Node.js Buffer常用方法包括:
1、buf.write(string[, offset[, length]][, encoding])
將一個字元串寫入Buffer中,並返回已寫入的位元組數。可以指定偏移量和長度。
const buf = Buffer.alloc(10);
const bytesWritten = buf.write('hello', 1, 3, 'utf8'); // 在偏移量為1的位置寫入'hel',返回已寫入的位元組數 3
2、buf.toString([encoding[, start[, end]]])
將Buffer對象轉換為字元串。默認將Buffer對象的全部內容轉換為字元串。
const buf = Buffer.from('hello world', 'utf8');
const str = b.toString('utf8'); // 轉換成字元串'hello world'
3、buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
將Buffer的內容複製到另一個Buffer中。
const buf1 = Buffer.from('hello');
const buf2 = Buffer.alloc(10);
const bytesCopied = buf1.copy(buf2, 1, 0, 3); // 將buf1的偏移量0~3的內容複製到buf2的偏移量1~4的位置,返回已複製的位元組數 3
4、buf.slice([start[, end]])
創建一個新的Buffer對象,與原Buffer對象共享內存但指定偏移量和長度範圍。
const buf1 = Buffer.from('hello');
const buf2 = buf1.slice(1, 3); // 創建一個新的Buffer實例,包含buf1的偏移量1~2的內容,即'el'
5、buf.toJSON()
返回一個將Buffer對象轉換成JSON對象後的結果。
const buf = Buffer.from('hello');
const json = buf.toJSON(); // 轉換成JSON對象
console.log(json); // { type: 'Buffer', data: [ 104, 101, 108, 108, 111 ] }
五、Node.js Buffer應用示例
1、文件讀取
const fs = require('fs');
fs.readFile('test.txt', (err, buf) => {
if (err) {
console.error(err);
return;
}
const str = buf.toString('utf8');
console.log(str);
});
2、字元串加密
const crypto = require('crypto');
const str = 'hello world';
const hash = crypto.createHash('md5');
const buf = Buffer.from(str, 'utf8');
hash.update(buf);
console.log(hash.digest('hex'));
3、獲取網路請求體的二進位數據
const http = require('http');
http.createServer((req, res) => {
let chunks = [];
req.on('data', chunk => {
chunks.push(chunk);
});
req.on('end', () => {
const buf = Buffer.concat(chunks);
console.log(buf.toString('utf8'));
res.end('success');
});
}).listen(8000);
六、Node.js Buffer小結
Node.js Buffer提供了處理二進位數據的能力,可以用於處理文件流、網路流、加密等場景。Buffer的常用方法包括write、toString、copy、slice和toJSON等。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/158430.html