• Node.js Video Tutorials

Node.js - Buffer.toJSON() 方法



NodeJS 的 Buffer.toJSON() 方法返回給定緩衝區的 JSON 物件。

語法

以下是 Node.JS Buffer.toJSON() 方法 的語法:

buf.toJSON()

引數

此方法沒有任何引數。

返回值

方法 buffer.toJSON() 返回一個 json 物件。

示例

要建立緩衝區,我們將使用 NodeJS Buffer.from() 方法:

const buffer = Buffer.from('Hello');
console.log(buffer.toJSON());

緩衝區是用字串“Hello”建立的。

輸出

{ type: 'Buffer', data: [ 72, 101, 108, 108, 111 ] }

示例

在此示例中,緩衝區是用數字陣列建立的。Buffer.toJSON() 的輸出如下所示:

const buffer = Buffer.from([1,2,3,4,5,6,7,8,9,10]);
console.log(buffer.toJSON());

輸出

{ type: 'Buffer', data: [
   1, 2, 3, 4,  5,
   6, 7, 8, 9, 10
] }

您也可以在建立的 Buffer 上使用 JSON.stringify() 方法。

const buffer = Buffer.from([1,2,3,4,5,6,7,8,9,10]);
console.log(JSON.stringify(buffer));

輸出

{"type":"Buffer","data":[1,2,3,4,5,6,7,8,9,10]}

示例

在此示例中,我們將使用 Buffer.alloc() 並用一個值填充它。

const buffer = Buffer.alloc(10);
buffer.fill('H');
console.log(buffer.toJSON());

輸出

{
   type: 'Buffer',
   data: [
      72, 72, 72, 72, 72,
      72, 72, 72, 72, 72
   ]
}
nodejs_buffer_module.htm
廣告