Node.js | Buffer.toJSON() Method

Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like the array of integers.

The Buffer.toJSON() method returns the buffer in JSON format.

Note: The JSON.Stringify() is the method which can also be used to return the data in JSON format. When we call the JSON.Stringify() method, it directly in the background calls the buffer.toJSON() Method.



Syntax:

buffer.toJSON()

Return Value: It returns the buffer in JSON format.

Below examples illustrate the use of Buffer.toJSON() method in Node.js:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the  
// Buffer.toJSON() Method
  
var buffer = Buffer.from('GeeksforGeeks');
   
// Prints: the ascii values of each
// character of 'GeeksforGeeks'
console.log(buffer.toJSON());

chevron_right


Output:

{
  type: 'Buffer',
  data: [
     71, 101, 101, 107,
    115, 102, 111, 114,
     71, 101, 101, 107,
    115
  ]
}

Example 2: This example implements the use of JSON.Stringify() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the  
// Buffer.toJSON() Method
  
const buffer = Buffer.from([1, 2, 3, 4]);
  
const output = JSON.stringify(buffer);
  
// Prints: {"type":"Buffer", "data":[1, 2, 3, 4]}
console.log(output);

chevron_right


Output:

{"type":"Buffer", "data":[1, 2, 3, 4]}

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/buffer.html#buffer_buf_tojson



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.