前言
在需要处理二进制数据时,Node.js 提供了 Buffer 对象,Buffer 对象是 Node.js 中处理二进制数据的核心模块。Buffer 对象类似于数组,但是它可以存储不同类型的数据,如整数、浮点数和字符串等。使用 Buffer 可以方便地进行二进制数据的操作,例如读写文件、处理网络协议等。
本文将介绍 Buffer 对象的基本用法以及一些高级用法,希望能够让读者了解如何在 Node.js 中使用 Buffer 处理二进制数据。
Buffer 对象的基本用法
创建 Buffer 对象
可以通过多种方式创建 Buffer 对象,例如:
// www.javascriptcn.com code example // 创建一个包含字符串的 Buffer 对象 const str = 'hello, world!'; const buf1 = Buffer.from(str); // 创建指定长度的 Buffer 对象 const buf2 = Buffer.alloc(10); // 10 字节的空间 // 创建包含数据的 Buffer 对象 const buf3 = Buffer.from([0x12, 0x34, 0x56]);
刚才创建了三个 Buffer 对象,分别是通过字符串、指定长度和数组创建的。可以使用 console.log 打印出这些 Buffer 对象:
console.log(buf1); // <Buffer 68 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21> console.log(buf2); // <Buffer 00 00 00 00 00 00 00 00 00 00> console.log(buf3); // <Buffer 12 34 56>
可以看到,Buffer 对象存储的数据是以十六进制的形式显示的。
读取 Buffer 对象中的数据
可以使用数组下标来读取 Buffer 对象中的数据,例如:
const buf = Buffer.from([0x12, 0x34, 0x56]); console.log(buf[0]); // 18 console.log(buf[1]); // 52 console.log(buf[2]); // 86
Buffer 对象的索引从 0 开始,读取时可以直接使用数组下标来获取数据。
写入数据到 Buffer 对象中
可以使用数组下标或 write 方法将数据写入 Buffer 对象中,例如:
// www.javascriptcn.com code example
const buf = Buffer.alloc(3);
buf[0] = 0x12;
buf[1] = 0x34;
buf[2] = 0x56;
console.log(buf); // <Buffer 12 34 56>
buf.write('abc');
console.log(buf); // <Buffer 61 62 63>write 方法可以将字符串写入 Buffer 对象中,可以通过第二个参数指定写入的位置和长度,例如:
const buf = Buffer.alloc(6);
buf.write('hello', 0, 'hello'.length);
buf.write('world', 2, 'world'.length);
console.log(buf); // <Buffer 68 65 77 6f 72 6c>这里通过第二个参数指定了 hello 字符串写入的位置和长度,通过第三个参数指定了 world 字符串写入的位置和长度。
获取 Buffer 对象的长度
可以使用 length 属性获取 Buffer 对象的长度,例如:
const buf = Buffer.from('hello, world!');
console.log(buf.length); // 13Buffer 对象的高级用法
拼接多个 Buffer 对象
在处理网络数据、文件数据等时,有时需要将多个 Buffer 对象拼接在一起,可以使用 concat 方法实现。
const buf1 = Buffer.from('hello');
const buf2 = Buffer.from(', ');
const buf3 = Buffer.from('world');
const buf4 = Buffer.from('!');
const buf = Buffer.concat([buf1, buf2, buf3, buf4]);
console.log(buf.toString()); // hello, world!切割 Buffer 对象
在处理网络数据、文件数据等时,有时需要将 Buffer 对象进行分割,可以使用 slice 方法实现。
const buf = Buffer.from('hello, world!');
const buf1 = buf.slice(0, 5);
const buf2 = buf.slice(7, 13);
console.log(buf1.toString()); // hello
console.log(buf2.toString()); // world!转换数据类型
在处理网络数据、文件数据等时,有时需要将 Buffer 对象转换为其他数据类型,或者将其他数据类型转换为 Buffer 对象,可以使用一系列方法实现。
例如,可以使用 toString 方法将 Buffer 对象转换为字符串:
const buf = Buffer.from('hello, world!');
console.log(buf.toString()); // hello, world!可以使用 JSON.stringify 和 JSON.parse 方法将 Buffer 对象转换为 JSON 对象和字符串:
// www.javascriptcn.com code example
const buf = Buffer.from('hello, world!');
const json = JSON.stringify(buf);
console.log(json); // {"type":"Buffer","data":[104,101,108,108,111,44,32,119,111,114,108,100,33]}
const buf2 = JSON.parse(json, (key, value) => {
if (value && value.type === 'Buffer') {
return Buffer.from(value.data);
}
return value;
});
console.log(buf2.toString()); // hello, world!可以使用 Buffer.from 和 Buffer.alloc 方法将其他数据类型转换为 Buffer 对象,例如:
const str = 'hello, world!'; const buf = Buffer.from(str, 'utf8'); console.log(buf); // <Buffer 68 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21> const buf2 = Buffer.alloc(3, 0x12); console.log(buf2); // <Buffer 12 12 12>
使用 Stream 处理数据
在处理大量的二进制数据时,可以使用 Node.js 的 Stream 来实现。
// www.javascriptcn.com code example
const fs = require('fs');
const rs = fs.createReadStream('./input.txt');
const ws = fs.createWriteStream('./output.txt');
rs.on('data', (chunk) => {
ws.write(chunk);
});
rs.on('end', () => {
ws.end();
});
ws.on('finish', () => {
console.log('done');
});这里创建了一个可读流和一个可写流,将 ./input.txt 中的数据写入 ./output.txt 中。
使用 Buffer 实现加密、解密功能
在处理加密、解密等功能时,可以使用 crypto 模块提供的加密、解密函数配合 Buffer 来实现。
// www.javascriptcn.com code example
const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const password = '12345678';
const iv = crypto.randomBytes(16);
const encrypt = (text) => {
const cipher = crypto.createCipheriv(algorithm, password, iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return { iv: iv.toString('hex'), content: encrypted.toString('hex') };
};
const decrypt = (iv, encryptedText) => {
const decipher = crypto.createDecipheriv(algorithm, password, Buffer.from(iv, 'hex'));
const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedText, 'hex')), decipher.final()]);
return decrypted.toString();
};
const text = 'hello, world!';
const encrypted = encrypt(text);
console.log(encrypted); // { iv: 'a48fd84fd48f0cf8eab682084b937c04', content: 'd4f803ad5ca05bf5d5e5e5d5fe' }
const decrypted = decrypt(encrypted.iv, encrypted.content);
console.log(decrypted); // hello, world!这里使用 AES 加密算法和 CBC 分组模式,使用密码 12345678 加密 hello, world! 的明文,将加密结果和初始化向量一起输出。然后使用初始化向量和加密结果进行解密,输出解密结果。
结语
通过这篇文章,我们了解了如何在 Node.js 中使用 Buffer 处理二进制数据,包括创建 Buffer 对象、读取和写入数据、拼接和切割 Buffer 对象以及转换数据类型等基本用法,还学习了使用 Stream 处理数据和使用 Buffer 实现加密、解密功能等高级用法。希望这些内容对读者有帮助。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c3a91f314edc2684dbb386