Mariik
Mariik

Reputation: 135

Hw to store Objects in Node.js Buffer?

Is it possible to store object in Buffer? The only option I see for now is to store response from JSON.stringify({})

code like this:

const objectBuffer = Buffer.from({id:123})

Throws an error:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object

Upvotes: 0

Views: 917

Answers (1)

tmarwen
tmarwen

Reputation: 16354

As the Node.js platform official documentation states:

Static method: Buffer.from(object[, offsetOrEncoding[, length]])#

Added in: v8.2.0 object An object supporting Symbol.toPrimitive or valueOf(). offsetOrEncoding | A byte-offset or encoding. length A length.

The object being passed as the first argument needs to either support Symbol.toPrimitive or valueOf(). Here down a basic example copied from the documentation:

import { Buffer } from 'buffer';

class Foo {
  [Symbol.toPrimitive]() { // the symbol converting the object to the primitive value and used by the `Buffer` under the hood
    return 'this is a test';
  }
}

const buf = Buffer.from(new Foo(), 'utf8');
// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>

The common used alternative is stringifying the object as you did and passing the string result to the static variant Buffer.from(string[, encoding]).

Upvotes: 1

Related Questions