node.js 中的 buffer 用于处理原始二进制数据,这在处理流、文件或网络数据时非常有用。
const buf = buffer.from('hello');
const buf = buffer.alloc(10); // 10-byte buffer filled with zeros
const buf = buffer.from([72, 101, 108, 108, 111]); // represents 'hello'
const buf = buffer.from('hello'); console.log(buf.tostring()); // 'hello'
const buf = buffer.from('hello'); console.log(buf.length); // 5 (each character takes 1 byte)
const buf = buffer.alloc(5); buf.write('hi'); console.log(buf.tostring()); // 'hi'
const buf = buffer.from('hello world'); const slice = buf.slice(null, 5); console.log(slice.tostring()); // 'hello'
const buf1 = buffer.from('hello'); const buf2 = buffer.alloc(5); buf1.copy(buf2); console.log(buf2.tostring()); // 'hello'
const buf1 = buffer.from('abc'); const buf2 = buffer.from('abc'); console.log(buf1.equals(buf2)); // true
const buf1 = Buffer.from('Hello'); const buf2 = Buffer.from(' World'); const buf3 = Buffer.concat([buf1, buf2]); console.log(buf3.toString()); // 'Hello World'
这些是开始在 node.js 中处理二进制数据时需要了解的关键 buffer 函数:
这足以处理 node.js 中的大多数初学者用例!