Node.js Buffer.from() 方法
Buffer.from() 方法用于创建包含指定字符串、数组或缓冲区的新缓冲区。
句法:
Buffer.from( object, encoding )
参数:此方法接受上面提到的两个参数,如下所述:
- object:此参数可以保存字符串、缓冲区、数组或数组缓冲区。
- encoding:如果对象是一个字符串,那么它用于指定其编码。它是可选参数。它的默认值为 utf8。
示例 1:
// Node.js program to demonstrate the
// Buffer.from() Method
// Returns a new buffer with
// copy of the given string
var buf1 = Buffer.from("hello");
// Display the buffer object
// of the given string
console.log(buf1);
// Convert the buffer to the
// string and displays it
console.log(buf1.toString());
输出:
hello
示例 2:
// Node.js program to demonstrate the
// Buffer.from() Method
// Creates an arrayBuffer with
// length 10
var arbuff = new ArrayBuffer(8);
// Returns a new buffer with a
// specified memory range within
// the arrayBuffer
var buf = Buffer.from(arbuff, 0, 2);
// Displays the length
console.log(buf.length);
输出:
2
示例 3:
// Node.js program to demonstrate the
// Buffer.from() Method
// Create a new buffer with
// copy of the given string
var buf1 = Buffer.from("John");
// Create another buffer with
// copy of given buffer
var buf2 = Buffer.from(buf1);
// Display the buffer object
console.log(buf2);
// Convert the buffer to
// string and displays it
console.log(buf2.toString());
输出:
John
注意:以上程序将使用node index.js
命令编译运行。
参考: https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding