Instructions for the buffer.toJSON method in node.js

  • 2020-05-05 10:53:00
  • OfStack

method description:

Converts buffer objects to json format.

syntax:


buffer.toJSON()

receive parameters:

No

Example:


var buf = new Buffer('test');
var json = JSON.stringify(buf);
console.log(json);
// '{"type":"Buffer","data":[116,101,115,116]}'
var copy = JSON.parse(json, function(key, value) {
    return value && value.type === 'Buffer'
      ? new Buffer(value.data)
      : value;
  });
console.log(copy);
// <Buffer 74 65 73 74>

source code:


Buffer.prototype.toJSON = function() {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this, 0)
  };
};


Related articles: